package com.yunxi.service.dubboService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.github.pagehelper.PageInfo;
import com.yunxi.account.pojo.PartnerAccountInfoReqVO;
import com.yunxi.account.pojo.PartnerAccountInfoRespVO;
import com.yunxi.account.pojo.PartnerAmountRespVO;
import com.yunxi.baseDataToHub.pojo.app.OrderStatusVO;
import com.yunxi.baseDataToHub.pojo.sap.PartnerFundVO;
import com.yunxi.baseDataToHub.pojo.sap.VehicleBatchOrderModifyVO;
import com.yunxi.baseDataToHub.pojo.sap.VehicleBatchOrderVO;
import com.yunxi.baseDataToHub.pojo.sap.VehiclePriceCountVo;
import com.yunxi.baseDataToHub.service.app.AppDubboService;
import com.yunxi.baseDataToHub.service.sap.SapDubboService;
import com.yunxi.bizToBaseData.pojo.AttachReqVO;
import com.yunxi.bizToBaseData.pojo.PartnerInfoReqVO;
import com.yunxi.bizToBaseData.pojo.PartnerInfoRespVO;
import com.yunxi.bizToBaseData.pojo.VehiclePriceReqVO;
import com.yunxi.bizToBaseData.service.STOSPartnerDubboService;
import com.yunxi.bizToBaseData.service.SToSAttachDubboService;
import com.yunxi.bizToBaseData.service.SToSVehiclePriceDubboService;
import com.yunxi.bizToHub.pojo.OtdOptionVO;
import com.yunxi.core.base.Constant;
import com.yunxi.core.enums.DMSEnumsEntity;
import com.yunxi.core.util.DateUtil;
import com.yunxi.core.util.GUIDGenerator;
import com.yunxi.core.util.StringUtil;
import com.yunxi.core.util.WgrDate;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.freeze.AmountFreeze;
import com.yunxi.model.freeze.PartnerAccount;
import com.yunxi.model.freeze.PartnerAmountFreezeFlow;
import com.yunxi.model.order.*;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.model.vip.StoVehicleExp;
import com.yunxi.order.pojo.*;
import com.yunxi.order.service.OrderOemManagerDubboService;
import com.yunxi.service.localService.*;
import com.yunxi.service.localService.impl.CodeCreateServiceImpl;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.service.localService.vip.StoVehicleExpService;
import com.yunxi.sto.service.StoTransportPlanDubboService;
import com.yunxi.sto.service.VehiclePdiBillDubboService;
import com.yunxi.vehicle.pojo.VehicleCertReqVO;
import com.yunxi.vehicle.pojo.VehicleCertRespVO;
import com.yunxi.vehicle.pojo.VehicleProductViewVO;
import com.yunxi.vehicle.service.VehiclePackageDubboService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.yunxi.vip.pojo.StoVehicleExpVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

public class OrderOemManagerDubboServiceImpl implements OrderOemManagerDubboService {

    private final Logger logger = LoggerFactory.getLogger(OrderOemManagerDubboServiceImpl.class);

    @Autowired
    SapDubboService sapDubboServiceImpl;

    @Autowired
    SToSAttachDubboService stosAttachDubboService;

    @Autowired
    STOSPartnerDubboService stosPartnerDubboService;

    @Autowired
    StoTransportPlanDubboService stoTransportPlanDubboServiceReference;

    @Autowired
    private Mapper dozerMapper;

    @Autowired
    @Qualifier(value = "orderOemManageCustomerServiceImpl")
    OrderOemManagerCustomerService orderOemManageCustomerServiceImpl;


    /**
     * 批售单子订单业务层
     */
    @Autowired
    @Qualifier(value = "orderVehicleServiceImpl")
    OrderVehicleService orderVehicleServiceImpl;

    /**
     * 批售订单业务层
     */
    @Autowired
    @Qualifier(value = "orderOemServiceImpl")
    OrderOemService orderOemServiceImpl;

    /**
     *
     */
    @Autowired
    @Qualifier(value = "orderApproveCustomerServiceImpl")
    OrderApproveCustomerService orderApproveCustomerServiceImpl;

    @Autowired
    @Qualifier(value = "vehicleCertCustomerServiceImpl")
    VehicleCertCustomerService vehicleCertCustomerServiceImpl;

    @Autowired
    @Qualifier(value = "orderVehicleRejectServiceImpl")
    OrderVehicleRejectService orderVehicleRejectServiceImpl;

    @Autowired
    @Qualifier(value = "orderApproveAutoMatchCarServiceImpl")
    OrderApproveAutoMatchCarService orderApproveAutoMatchCarServiceImpl;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineServiceImpl;

    @Autowired
    @Qualifier(value = "vehicleProductViewServiceImpl")
    VehicleProductViewService vehicleProductViewServiceImpl;

    @Autowired
    @Qualifier(value = "orderCancelReasonServiceImpl")
    OrderCancelReasonService orderCancelReasonServiceImpl;

    @Autowired
    @Qualifier(value = "orderModifyApplyServiceImpl")
    OrderModifyApplyService orderModifyApplyServiceImpl;

    @Autowired
    @Qualifier(value = "amountFreezeServiceImpl")
    AmountFreezeService amountFreezeServiceImpl;

    @Autowired
    @Qualifier(value = "partnerAccountInfoServiceImpl")
    PartnerAccountInfoService partnerAccountInfoServiceImpl;

    @Autowired
    @Qualifier(value = "partnerAmountFreezeFlowServiceImpl")
    PartnerAmountFreezeFlowService partnerAmountFreezeFlowServiceImpl;

    /**
     * 序列号生成器
     */
    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateService codeCreateServiceImpl;

    @Autowired
    SToSVehiclePriceDubboService stoSVehiclePriceDubboServiceImpl;

    @Autowired
    @Qualifier("orderCustomerServiceImpl")
    OrderCustomerService orderCustomerService;

    /**
     * 批售单子订单业务层
     */
    @Autowired
    @Qualifier(value = "stoVehicleExpServiceImpl")
    StoVehicleExpService stoVehicleExpService;

    @Autowired
    @Qualifier(value = "vehiclePdiBillDubboServiceImpl")
    VehiclePdiBillDubboService vehiclePdiBillDubboService;

    @Autowired
    AppDubboService appDubboService;

    @Autowired
    VehiclePackageDubboService vehiclePackageDubboService;



    /**
     * 分页查询批售单信息
     *
     * @param vo
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Transactional
    @Override
    public PageInfo<OrderOemRespVO> queryPmsOrderOemForPage(OrderOemReqVO vo, int pageIndex, int pageSize) {
        PageInfo<OrderOemRespVO> pageInfo = orderOemManageCustomerServiceImpl.queryPmsOrderOemForPage(vo, pageIndex, pageSize);
        return pageInfo;
    }

    @Override
    public PageInfo<ModifyOrderRespVO> queryModifyOrderForPage(ModifyOrderReqVO vo, int pageNum, int pageSize) {
        PageInfo<ModifyOrderRespVO> pageInfo = orderOemManageCustomerServiceImpl.queryModifyOrderForPage(vo, pageNum, pageSize);
        return pageInfo;
    }


    /**
     * 批售单详情查询
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public OrderOemDetailsRespVO queryOrderOemDetails(OrderOemDetailsReqVO vo) {
        OrderOemDetailsRespVO detail = orderOemManageCustomerServiceImpl.queryOrderOemDetails(vo);
        return detail;
    }

    /**
     * 批售单明细查询（已提交）
     *
     * @param vo        查询条件
     * @param pageIndex 当前页
     * @param pageSize  每页显示数据行数
     * @return
     */
    @Override
    @Transactional
    public PageInfo<OrderOemDetailsAlreadySubmitRespVO> queryOrderOemDetailsAlreadySubmitForPage(OrderOemDetailsAlreadySubmitReqVO vo, int pageIndex, int pageSize) {
        PageInfo<OrderOemDetailsAlreadySubmitRespVO> pageInfo = orderOemManageCustomerServiceImpl.queryOrderOemDetailsAlreadySubmitForPage(vo, pageIndex, pageSize);

        return pageInfo;
    }

    /**
     * 批售单/寄售单提交
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean submitOrderVehicle(OrderVehicleSubmitReqVO vo) {

        if (vo == null || vo.getOrderIds() == null) {
            logger.info("VO对象为空，提交批售或寄售单失败！");
            throw new RuntimeException("VO对象为空，提交批售或寄售单失败！");
        }

        List<OrderVehicle> pmsOrderVehicle = new ArrayList<>();
        for (String orderId : vo.getOrderIds()) {

            QueryWrapper qw = new QueryWrapper();
            qw.eq("ORDER_ID", orderId);
            PmsOrderOem pmsOrderOem = orderOemServiceImpl.getOne(qw);

            for (int i = 0; i < pmsOrderOem.getNum(); i++) {
                //
                //保存车辆订单信息
                OrderVehicle orderVehicle = new OrderVehicle();
                BeanUtils.copyProperties(vo, orderVehicle);
                BeanUtils.copyProperties(pmsOrderOem, orderVehicle);
                //
                //生成车辆订单号
                String ocCode = codeCreateServiceImpl.createCode("OC", 4);
                orderVehicle.setOrderCarId(ocCode);
                orderVehicle.setOrderId(pmsOrderOem.getOrderId());
                orderVehicle.setPriorityLevel(Constant.PMS_ORDER_VEHICLE_LEVEL_MIDDLE);
                orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_AUDIT);
                orderVehicle.setMatchStatus(Constant.PMS_ORDER_VEHICLE_MATCH_STATUS_NO_MATCH_CAR);
                orderVehicle.setProductCode(pmsOrderOem.getProductCode());
                orderVehicle.setCreateBy(vo.getUserCode());
                orderVehicle.setCreateDate(new Date());
                orderVehicle.setDiscountProportion(vo.getDiscountProportion());
                orderVehicle.setSpecialDiscountProportion(vo.getSpecialDiscountProportion());
                //   获取选装包中文
                String customPackNames = vehiclePackageDubboService.strByNodeCodeIn(StringUtil.customSqlStr(pmsOrderOem.getCustomPackCodes()));
                orderVehicle.setCustomPackNames(customPackNames);
                //如果有 折扣计算折扣后结算价格   结算价格 = 结算价格 *（1-折扣比例） 或者  结算价格 = 结算价格 - 折扣金额
                if(vo.getDiscountProportion()!=null || vo.getSpecialDiscountProportion()!=null){
                    //比例
                    if(vo.getDiscountProportion()!=null){
                        BigDecimal rate =  vo.getDiscountProportion().divide(new BigDecimal(100));
                        BigDecimal  deltaVlaue =  orderVehicle.getSettlementPrice().multiply(rate);
                        orderVehicle.setSettlementPrice( orderVehicle.getSettlementPrice().subtract(deltaVlaue) );
                        orderVehicle.setPreferentialPrice(orderVehicle.getPreferentialPrice().subtract(deltaVlaue));
                    }
                    //固定值
                    if(vo.getSpecialDiscountProportion()!=null){
                        orderVehicle.setSettlementPrice( orderVehicle.getSettlementPrice().subtract(vo.getSpecialDiscountProportion()) );
                        orderVehicle.setPreferentialPrice(orderVehicle.getPreferentialPrice().subtract(vo.getSpecialDiscountProportion()));
                    }
                }

                boolean isSuccessByOrderVehicle = orderVehicleServiceImpl.save(orderVehicle);

                if (!isSuccessByOrderVehicle) {
                    logger.info("提交批售单或寄售单，拆单失败，事务回滚！");
                    throw new RuntimeException("提交批售单或寄售单，拆单失败，事务回滚！");
                }
            }

            pmsOrderOem.setCheckStatus(Constant.PMS_ORDER_OEM_CHECK_STATUS_SUBMIT);
            if (!orderOemServiceImpl.update(pmsOrderOem, qw)) {
                logger.info("提交批售或寄售单失败，事务回滚！");
                throw new RuntimeException("提交批售或寄售单失败，事务回滚！");
            }
        }
        return true;
    }

    @Transactional
    public boolean submitOrderVehicleByVip(OrderVehicleSubmitReqVO vo) {

        if (vo == null || vo.getOrderIds() == null) {
            logger.info("VO对象为空，提交批售或寄售单失败！");
            throw new RuntimeException("VO对象为空，提交批售或寄售单失败！");
        }

        List<OrderVehicle> pmsOrderVehicle = new ArrayList<>();
        for (String orderId : vo.getOrderIds()) {

            QueryWrapper qw = new QueryWrapper();
            qw.eq("ORDER_ID", orderId);
            PmsOrderOem pmsOrderOem = orderOemServiceImpl.getOne(qw);

            for (int i = 0; i < pmsOrderOem.getNum(); i++) {
                //
                //保存车辆订单信息
                OrderVehicle orderVehicle = new OrderVehicle();
                BeanUtils.copyProperties(vo, orderVehicle);
                BeanUtils.copyProperties(pmsOrderOem, orderVehicle);
                //
                //生成车辆订单号
                String ocCode = codeCreateServiceImpl.createCode("OC", 4);
                orderVehicle.setOrderCarId(ocCode);
                orderVehicle.setOrderId(pmsOrderOem.getOrderId());
                orderVehicle.setPriorityLevel(Constant.PMS_ORDER_VEHICLE_LEVEL_MIDDLE);
                orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_AUDIT);
                orderVehicle.setMatchStatus(Constant.PMS_ORDER_VEHICLE_MATCH_STATUS_NO_MATCH_CAR);
                orderVehicle.setProductCode(pmsOrderOem.getProductCode());
                orderVehicle.setCreateBy(vo.getUserCode());
                orderVehicle.setDiscountProportion(vo.getDiscountProportion());
                orderVehicle.setSpecialDiscountProportion(vo.getSpecialDiscountProportion());
                orderVehicle.setVipId(vo.getVipId());
                orderVehicle.setVehiclePurpose(1);
                orderVehicle.setType(vo.getType());
                if(StringUtils.isNotEmpty(vo.getPartnerCode())){
                    orderVehicle.setPartnerCode(vo.getPartnerCode());
                }else{
                    orderVehicle.setPartnerCode(vo.getPartnerFinance());
                }

                //orderVehicle.setDiscountProportion();
                boolean isSuccessByOrderVehicle = orderVehicleServiceImpl.save(orderVehicle);

                //保存租赁列表
                //if(vo.getBusinessType().equals("5")){
                StoVehicleExp ve = new StoVehicleExp();
                ve.setExpId(GUIDGenerator.getPrimaryKey());
                ve.setPartnerCode(vo.getPartnerCode());
                ve.setPartnerFinance(vo.getPartnerFinance());
                ve.setDetailId(vo.getDetailId());
                ve.setOrderVehicleId(orderVehicle.getOrderCarId());
                ve.setBusinessType(vo.getBusinessType());
                ve.setCheckSalesStatus(vo.getSubmitType());
                stoVehicleExpService.save(ve);

                if (!isSuccessByOrderVehicle) {
                    logger.info("提交批售单或寄售单，拆单失败，事务回滚！");
                    throw new RuntimeException("提交批售单或寄售单，拆单失败，事务回滚！");
                }
                //}
            }

            pmsOrderOem.setCheckStatus(Constant.PMS_ORDER_OEM_CHECK_STATUS_SUBMIT);
            if (!orderOemServiceImpl.update(pmsOrderOem, qw)) {
                logger.info("提交批售或寄售单失败，事务回滚！");
                throw new RuntimeException("提交批售或寄售单失败，事务回滚！");
            }
        }
        return true;
    }

    /**
     * 修改订单审核,审核状态修改
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean updateOrderModifyApplyForCheckStatus(OrderModifyApplyReqVO vo) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_EDIT_ID", vo.getOrderEditId());

        OrderModifyApply orderModifyApply = new OrderModifyApply();
        orderModifyApply.setCheckStatus(vo.getCheckStatus());
        orderModifyApply.setAuditDate(new Date());
        orderModifyApply.setAuditBy(vo.getUserCode());
        orderModifyApply.setUpdateBy(vo.getUserCode());
        orderModifyApply.setRejectInfo(vo.getRejectInfo());
        boolean isSuccess = orderModifyApplyServiceImpl.update(orderModifyApply, qw);

        if(vo.getCheckStatus() == 1){ //审核通过,调用整车批售订单修改接口

            OrderModifyApply entity = orderModifyApplyServiceImpl.getOne(qw);

            //
            //更新批售单表地址信息，联系人，联系方式
            OrderVehicle upOrderVehicle = new OrderVehicle();
            upOrderVehicle.setStorageCode(entity.getStorageCode());
            upOrderVehicle.setLinkman(entity.getLinkman());
            upOrderVehicle.setLinkphone(entity.getLinkphone());
            QueryWrapper qwUpdateOrderVehicle = new QueryWrapper();
            qwUpdateOrderVehicle.eq("ORDER_CAR_ID",entity.getOrderCarId());
            orderVehicleServiceImpl.update(upOrderVehicle,qwUpdateOrderVehicle);
            QueryWrapper qwOrderVehicle = new QueryWrapper();
            qwOrderVehicle.eq("ORDER_CAR_ID",entity.getOrderCarId());

            OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);
            callSapInvokByModifyPms2Sap(orderVehicle);
        }

        if (isSuccess) {
            return true;
        } else {
            logger.info("修改订单审核状态失败！");
            throw new RuntimeException("修改订单审核状态失败！");
        }
    }

    /**
     * 整车批售订单修改接口
     * 修改订单申请通过或取消订单申请通过后调用SAP接口
     */
    private boolean callSapInvokByModifyPms2Sap( OrderVehicle orderVehicle){

        VehicleBatchOrderModifyVO vehicleBatchOrderModifyVO = new VehicleBatchOrderModifyVO();
        vehicleBatchOrderModifyVO.setVbeln(orderVehicle.getSapOrderNo());//SAP销售订单号
        vehicleBatchOrderModifyVO.setCertfadd(orderVehicle.getAddr()); //合格证邮寄地址
        vehicleBatchOrderModifyVO.setDealeradd(orderVehicle.getAddr());//收车地址
        vehicleBatchOrderModifyVO.setEtdat(WgrDate.date2Str(orderVehicle.getDispatchDate(),"yyyy-MM-dd")); //发运日期
        vehicleBatchOrderModifyVO.setBstkd(orderVehicle.getOrderCarId());
        vehicleBatchOrderModifyVO.setVhvin(orderVehicle.getVin());
        vehicleBatchOrderModifyVO.setIndicator("1");
        ApiResult sapResult =  null ;
        try {
             sapResult = sapDubboServiceImpl.sendVehicleBatchOrderModifyPms2Sap(vehicleBatchOrderModifyVO);

            if (200 != sapResult.getCode()) {
                logger.error("SAP接口调用，整车批售订单修改接口失败!");
                throw new RuntimeException("SAP整车批售订单修改接口调用失败！"+sapResult.getCode()+sapResult.getMsg());
            }

            JSONObject json = JSONObject.parseObject((String) sapResult.getData());

            orderVehicle.setOrderCarId((String) json.get("bstkd"));
            orderVehicle.setSapOrderNo((String) json.get("vbeln"));
            orderVehicle.setSapHandleDate((String) json.get("zdate"));
            orderVehicle.setSapHandleTime((String) json.get("ztime"));
            orderVehicle.setSapHandleStatus((String) json.get("zstat"));
            orderVehicle.setSapHandleMessage((String) json.get("zmess"));
            boolean isSuccess = orderVehicleServiceImpl.updateById(orderVehicle);
            return isSuccess;
        }catch(Exception e){
            logger.error("SAP整车批售订单修改接口调用失败！{}",e);
            throw new RuntimeException("SAP整车批售订单修改接口调用失败！"+sapResult.getCode()+sapResult.getMsg());
        }
    }

    /**
     * 取消订单审核，审核状态修改
     *
     * @return
     */
    @Override
    @Transactional
    public boolean updateOrderCancelReasonForCheckStatus(OrderCancelReasonReqVO vo) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("CANCEL_ID", vo.getCancelId());

        OrderCancelReason orderCancelReason = new OrderCancelReason();
        orderCancelReason.setCheckStatus(vo.getCheckStatus());
        orderCancelReason.setRejectInfo(vo.getRejectInfo());
        orderCancelReason.setAuditBy(vo.getUserCode());
        orderCancelReason.setAuditDate(new Date());
        boolean isSuccess = orderCancelReasonServiceImpl.update(orderCancelReason, qw);

        //如果取消申请通过后,更新订单状态为已取消
        if(vo.getCheckStatus() == Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_CHECK_PASS){
            OrderCancelReason reason = orderCancelReasonServiceImpl.getById(vo.getCancelId());
            if(reason != null) {
                QueryWrapper<OrderVehicle> qwOrderVehicle = new QueryWrapper<>();
                qwOrderVehicle.eq("ORDER_CAR_ID",reason.getOrderCarId());
                OrderVehicle tmpOrderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);

                //2019/09/22 解锁车辆
                if (!StringUtils.isEmpty(tmpOrderVehicle.getZordNo())) {
                    LambdaQueryWrapper<VehicleOffline> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(VehicleOffline::getZordNo, tmpOrderVehicle.getZordNo());
                    VehicleOffline car = vehicleOfflineServiceImpl.getOne(lambdaQueryWrapper);
                    if (car != null) {
                        car.setIsLock(0);
                    }
                    vehicleOfflineServiceImpl.updateById(car);
                }
                OrderVehicle orderVehicle = new OrderVehicle();
                orderVehicle.setOrderCarId(reason.getOrderCarId());
                orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_CANCEL);
                orderVehicle.setCheckDate(new Date());
                orderVehicleServiceImpl.updateById(orderVehicle);

                //
                //取消订单审核，审核通过后调用SAP整车批售订单修改接口
                callSapInvokByModifyPms2Sap(tmpOrderVehicle);
            }
        }

        if (isSuccess) {
            return true;
        } else {
            logger.info("修改取消订单审核的审核状态失败！");
            throw new RuntimeException("修改取消订单审核的审核状态失败！");
        }
    }

    /**
     * 修改保存批售单或寄售单
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean updatePmsOrderOem(OrderOemUpdateReqVO vo) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_ID", vo.getOrderId());

        PmsOrderOem pmsOrderOem = new PmsOrderOem();
        BeanUtils.copyProperties(vo, pmsOrderOem);

        boolean isSuccessByOrderOem = orderOemServiceImpl.update(pmsOrderOem, qw);
        if (isSuccessByOrderOem) {
            return true;
        } else {
            logger.info("修改保存批售单失败，事务回滚！");
            throw new RuntimeException("修改保存批售单失败，事务回滚！");
        }
    }

    /**
     * 价格试算
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public PriceTryComputeRespVO priceTryCompute(OrderOemSaveReqVO vo) {
//        PriceTryComputeRespVO priceResult = new PriceTryComputeRespVO();
//        priceResult.setPreferentialPrice(new BigDecimal("1000"));//优惠价
//        priceResult.setTaxesPrice(new BigDecimal("1000"));//税金
//        priceResult.setMarketPrice(new BigDecimal("11000")); //市场价
//        priceResult.setSettlementPrice(new BigDecimal("10000"));//结算价
//        return priceResult;

        PriceTryComputeRespVO respVO = priceTryCompute(null, vo);
        return respVO;
    }

    public PriceTryComputeRespVO priceTryCompute(String psCode, OrderOemSaveReqVO vo) {

        //
        //调用价格试算接口查询单据价格等相关信息
        VehiclePriceCountVo vehiclePriceCountVo = new VehiclePriceCountVo();
        vehiclePriceCountVo.setId(vo.getPriceTryCompute());
        vehiclePriceCountVo.setBstkd(psCode);
        vehiclePriceCountVo.setVkorg(Constant.PRICE_TRY_COMPUTE_ORGNIZE);//国内整车销售组织
        vehiclePriceCountVo.setKunnr(vo.getPartnerCode());//客户编码
        vehiclePriceCountVo.setCar_model(vo.getCatalogCode());//15位物料码
        //vehiclePriceCountVo.setZzpack(vo.getBatteryPackCode()); //电池包
        vehiclePriceCountVo.setPackage_no(vo.getCatalogCode()); //配置识别码,无任何实际意义
        vehiclePriceCountVo.setKwmeng("1");//数量
        vehiclePriceCountVo.setIndicator("N");
        vehiclePriceCountVo.setDiscount1(vo.getDiscountProportion());
        vehiclePriceCountVo.setDiscount2(vo.getSpecialDiscountProportion());
        List customPackCodeList = new ArrayList<>();
        if (StringUtils.isNotEmpty(vo.getCustomPackCodes())) {
            String[] customPackCodes = vo.getCustomPackCodes().split(",");
            for (int i = 0; i < customPackCodes.length; i++) {
                OtdOptionVO otdOptionVO = new OtdOptionVO();
                otdOptionVO.setCar_model(vo.getCatalogCode());
                otdOptionVO.setPackage_no(vo.getCatalogCode());//配置识别码,无任何实际意义
                otdOptionVO.setOption_code(customPackCodes[i]);
                customPackCodeList.add(otdOptionVO);
            }
            vehiclePriceCountVo.setOptions(customPackCodeList);
        }else{
            OtdOptionVO otdOptionVO = new OtdOptionVO();
            otdOptionVO.setCar_model(vo.getCatalogCode());
            otdOptionVO.setPackage_no(vo.getCatalogCode());//配置识别码,无任何实际意义
            otdOptionVO.setOption_code("");
            customPackCodeList.add(otdOptionVO);
            vehiclePriceCountVo.setOptions(customPackCodeList);
        }

        BigDecimal netwr = null;// 订单金额
        BigDecimal mwsbp = null;// 税金

        ApiResult sapResult=null;
        try {
             sapResult = sapDubboServiceImpl.sendVehiclePriceCountToSap(vehiclePriceCountVo);
            if (200 != sapResult.getCode()) {
                logger.error("SAP接口调用，价格试算出错，事务回滚!" + sapResult.getMsg());
                throw new RuntimeException("SAP接口调用，价格试算出错:" + sapResult.getMsg());
            }
            JSONObject json = JSONObject.parseObject((String) sapResult.getData());
            netwr = json.get("netwr") == null ? new BigDecimal(0) : (BigDecimal) json.get("netwr"); // 订单金额
            mwsbp = json.get("mwsbp") == null ? new BigDecimal(0) : (BigDecimal) json.get("mwsbp"); // 税金
            JSONArray jsonArray = json.getJSONArray("trialcond");

            //优惠价,结算价
            BigDecimal specialPrice = new BigDecimal(0);
            //指导价
            BigDecimal guidancePrice = new BigDecimal(0);
            for (int i = 0; jsonArray != null && i < jsonArray.size(); i++) {
                String val = jsonArray.getString(i);
                JSONObject jsonObj = JSONObject.parseObject(val);
                String condtype = jsonObj.getString("condtype");

                if ("ZD01".equals(condtype) || "ZD02".equals(condtype) || "ZD03".equals(condtype) || "ZD04".equals(condtype)
                        || "ZD05".equals(condtype) || "ZD06".equals(condtype) || "ZD07".equals(condtype)) {
                    specialPrice = specialPrice.add(new BigDecimal(jsonObj.getString("condvalue")));
                } else if ("ZPRR".equals(condtype) || "ZVAR".equals(condtype)) {
                    guidancePrice = guidancePrice.add(new BigDecimal(jsonObj.getString("condvalue")));
                }
            }
            //
            //优惠金额
           // BigDecimal specialAmount = guidancePrice.subtract(specialPrice);
            BigDecimal tlementPrice = new BigDecimal(0);
            tlementPrice=tlementPrice.add(netwr);
            tlementPrice=tlementPrice.add(mwsbp);
            PriceTryComputeRespVO priceResult = new PriceTryComputeRespVO();
            priceResult.setPreferentialPrice(netwr);
            priceResult.setTaxesPrice(mwsbp);
            priceResult.setMarketPrice(guidancePrice);
            priceResult.setPreferentialPrice(specialPrice);
            priceResult.setSettlementPrice(tlementPrice);
            //还差市场价、优惠金额需要补充
            return priceResult;

        } catch (Exception e) {
            String massage  ="SAP接口调用，价格试算出错，事务回滚!";
            if(sapResult!=null){
                massage = massage+sapResult.getCode()+ sapResult.getMsg();
            }

            logger.error(massage, e);
            throw new RuntimeException(massage);
        }
    }

    /**
     * 新增批售单或寄售单
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public boolean savePmsOrderOem(OrderOemSaveReqVO vo,LoginInfo loginInfo) {
        vo.setCustomPackCodes(StringUtil.customPackCodeSort(vo.getCustomPackCodes()));
        //表示渠道商创建
        if (vo.getOrderCreateType() == 1) {
            savePmsOrderOemEx(vo,loginInfo);
        } else if (vo.getOrderCreateType() == 2) {
            //
            //表示主机厂创建
            String psCode = savePmsOrderOemEx(vo,loginInfo);
            OrderVehicleSubmitReqVO orderVehicleSubmitReqVO = new OrderVehicleSubmitReqVO();
            List<String> orderIds = new ArrayList<>();
            orderIds.add(psCode);
            orderVehicleSubmitReqVO.setOrderIds(orderIds);
            orderVehicleSubmitReqVO.setUserCode(vo.getUserCode());
            orderVehicleSubmitReqVO.setVehiclePurpose(vo.getVehiclePurpose());
            orderVehicleSubmitReqVO.setDiscountProportion(vo.getDiscountProportion());
            orderVehicleSubmitReqVO.setSpecialDiscountProportion(vo.getSpecialDiscountProportion());
            orderVehicleSubmitReqVO.setCustomPackNames(vo.getCustomPackNames());
            submitOrderVehicle(orderVehicleSubmitReqVO);
        }


        return true;
    }

    private String savePmsOrderOemEx(OrderOemSaveReqVO vo, LoginInfo loginInfo) {
        //校验价格 非零非空
        int taxes =vo.getTaxesPrice().compareTo(BigDecimal.ZERO);
        int market =vo.getMarketPrice().compareTo(BigDecimal.ZERO);
        int settlement =vo.getSettlementPrice().compareTo(BigDecimal.ZERO);

        if(vo.getMarketPrice()==null ||market==0){
            //市场价
            logger.info("市场价为空，保存批售单失败！");
            throw new RuntimeException("市场价为空，保存批售单失败！");
        }else if(vo.getSettlementPrice()==null||settlement==0){
            //结算价
            logger.info("结算价为空，保存批售单失败！");
            throw new RuntimeException("结算价为空，保存批售单失败！");
        }else if(vo.getTaxesPrice()==null|| taxes == 0){
            //税金
            logger.info("税金为空，保存批售单失败！");
            throw new RuntimeException("税金为空，保存批售单失败！");
        }

        if (StringUtils.isEmpty(vo.getCatalogCode()) || StringUtils.isEmpty(vo.getColorCodeIn())
                || StringUtils.isEmpty(vo.getColorCodeOut())) {
            logger.info("查询条件为空【配置/内饰颜色/外饰颜色】，保存批售单失败！");
            throw new RuntimeException("查询条件为空【配置/内饰颜色/外饰颜色】，保存批售单失败！");
        }
        if (vo.getNum() <= 0) {
            logger.info("单据数量为空，保存批售单失败！");
            throw new RuntimeException("单据数量为空，保存批售单失败！");
        }
        //
        //生成批售单号
        String psCode = codeCreateServiceImpl.createCode(Constant.PMS_ORDER_OEM_NO_PREFIX, 4);

        //
        //根据车系、车型、配置、内饰颜色、外饰颜色查询车辆产品

        VehicleProductViewVO vehicleProductViewVO = vehicleProductViewServiceImpl.findProductBySub(vo.getCatalogCode(), vo.getColorCodeIn(), vo.getColorCodeOut());
        if (vehicleProductViewVO == null) {
            logger.info("没有相关车辆产品信息，创建批售单失败！");
            throw new RuntimeException("没有相关车辆产品信息，创建批售单失败！");
        }

//        PartnerInfoReqVO queryPartnerInfoVO = new PartnerInfoReqVO();
//        queryPartnerInfoVO.setPartnerCode(vo.getPartnerCode());
//        PartnerInfoRespVO partnerInfoRespVO = stosPartnerDubboService.queryPartnerInfoByCondition(queryPartnerInfoVO);

//        if (partnerInfoRespVO == null) {
//            throw new RuntimeException("获取订单类型失败！{}");
//        }

        //
        //保存批售单信息
        PmsOrderOem orderOem = new PmsOrderOem();
        BeanUtils.copyProperties(vo, orderOem);


        orderOem.setOrderId(psCode);
        orderOem.setColorCodeIn(vehicleProductViewVO.getColorCodeIn());
        orderOem.setColorNameIn(vehicleProductViewVO.getColorNameIn());
        orderOem.setColorCodeOut(vehicleProductViewVO.getColorCodeOut());
        orderOem.setColorNameOut(vehicleProductViewVO.getColorNameOut());
        orderOem.setCatalogCode(vehicleProductViewVO.getCatalogCode());
        orderOem.setCatalogName(vehicleProductViewVO.getCatalogName());
        orderOem.setSeriesCode(vehicleProductViewVO.getSeriesCode());
        orderOem.setSeriesName(vehicleProductViewVO.getSeriesName());
        orderOem.setModelCode(vehicleProductViewVO.getModelCode());
        orderOem.setModelName(vehicleProductViewVO.getModelName());
        orderOem.setProductCode(vehicleProductViewVO.getProductCode());
        orderOem.setProductName(vehicleProductViewVO.getProductName());

        //价格试算统一由前端调用
        orderOem.setMarketPrice(vo.getMarketPrice());
        orderOem.setSettlementPrice(vo.getSettlementPrice());
        orderOem.setTaxesPrice(vo.getTaxesPrice());
        orderOem.setPreferentialPrice(vo.getPreferentialPrice());
        //
        //0 未提交 1 已提交 2已取消
        orderOem.setCheckStatus(Constant.PMS_ORDER_OEM_CHECK_STATUS_UNSUBMIT);
//        orderOem.setType(partnerInfoRespVO.getType());
        orderOem.setType("1");//只有批售模式,场景值默认为1

        String[] customPackCodeArray = vo.getCustomPackCodes().split(",");

        CustomPackDetailsReqVO customPackDetailsReqVO = new CustomPackDetailsReqVO();
        customPackDetailsReqVO.setCustomPackCodes(customPackCodeArray);
        if(customPackCodeArray!=null&&customPackCodeArray.length>0)
        {
            List<CustomPackDetailsRespVO> customPackDetailsRespVO = orderOemManageCustomerServiceImpl.queryCustomPackDetails(customPackDetailsReqVO);
            //将装包数据明细存储为JSON字符串
            String customPackDetails = JSONObject.toJSONString(customPackDetailsRespVO);
            orderOem.setCustomPackDetails(customPackDetails);
        }

        //
        orderOem.setCreateBy(loginInfo.getUserCode());

        boolean isSuccess = orderOemServiceImpl.save(orderOem);
        if (!isSuccess) {
            logger.info("保存批售单主单失败，事务回滚！");
            throw new RuntimeException("保存批售单主单失败，事务回滚！");
        }
        return psCode;
    }

    @Override
    @Transactional
    public void savePmsOrderOemExByVip(OrderOemSaveReqVO vo, LoginInfo loginInfo) {

        if (StringUtils.isEmpty(vo.getCatalogCode()) || StringUtils.isEmpty(vo.getColorCodeIn())
                || StringUtils.isEmpty(vo.getColorCodeOut())) {
            logger.info("查询条件为空，保存批售单失败！");
            throw new RuntimeException("查询条件为空，保存批售单失败！");
        }
        if (vo.getNum() <= 0) {
            logger.info("单据数量为空，保存批售单失败！");
            throw new RuntimeException("单据数量为空，保存批售单失败！");
        }
        //
        //生成批售单号
        String psCode = codeCreateServiceImpl.createCode(Constant.PMS_ORDER_OEM_NO_PREFIX, 4);

        //根据车系、车型、配置、内饰颜色、外饰颜色查询车辆产品

        VehicleProductViewVO vehicleProductViewVO = vehicleProductViewServiceImpl.findProductBySub(vo.getCatalogCode(), vo.getColorCodeIn(), vo.getColorCodeOut());
        if (vehicleProductViewVO == null) {
            logger.info("没有相关车辆产品信息，创建批售单失败！");
            throw new RuntimeException("没有相关车辆产品信息，创建批售单失败！");
        }

        PartnerInfoReqVO queryPartnerInfoVO = new PartnerInfoReqVO();

        //判断当前是谁付款
        //如果渠道商为空，用金融伙伴，如果渠道商不为空用渠道
        if(StringUtils.isNotEmpty(vo.getPartnerCode())){
            queryPartnerInfoVO.setPartnerCode(vo.getPartnerCode());
        }else{
            queryPartnerInfoVO.setPartnerCode(vo.getPartnerFinancial());
        }

        PartnerInfoRespVO partnerInfoRespVO = stosPartnerDubboService.queryPartnerInfoByCondition(queryPartnerInfoVO);

        if (partnerInfoRespVO == null) {
            throw new RuntimeException("获取订单类型失败！{}");
        }

        //
        //保存批售单信息
        PmsOrderOem orderOem = new PmsOrderOem();
        BeanUtils.copyProperties(vo, orderOem);

        //暂时以前段为主，价格，后期需要以后端为主进行校验
//      Map<String,BigDecimal> tryResult = priceTryCompute(psCode,vo);
//
//        orderOem.setTotalPrice(tryResult.gey("netwr"));
////      orderOem.setTaxes(tryResult.gey("mwsbp"));
        //PriceTryComputeRespVO priceTryComputeRespVO = priceTryCompute(psCode, vo);
        orderOem.setOrderId(psCode);
        orderOem.setColorCodeIn(vehicleProductViewVO.getColorCodeIn());
        orderOem.setColorNameIn(vehicleProductViewVO.getColorNameIn());
        orderOem.setColorCodeOut(vehicleProductViewVO.getColorCodeOut());
        orderOem.setColorNameOut(vehicleProductViewVO.getColorNameOut());
        orderOem.setCatalogCode(vehicleProductViewVO.getCatalogCode());
        orderOem.setCatalogName(vehicleProductViewVO.getCatalogName());
        orderOem.setSeriesCode(vehicleProductViewVO.getSeriesCode());
        orderOem.setSeriesName(vehicleProductViewVO.getSeriesName());
        orderOem.setModelCode(vehicleProductViewVO.getModelCode());
        orderOem.setModelName(vehicleProductViewVO.getModelName());
        orderOem.setProductCode(vehicleProductViewVO.getProductCode());
        orderOem.setProductName(vehicleProductViewVO.getProductName());
        orderOem.setTaxes(vo.getTaxesPrice());
        orderOem.setMarketPrice(vo.getMarketPrice());
        orderOem.setSettlementPrice(vo.getSettlementPrice());
        orderOem.setTaxesPrice(vo.getTaxesPrice());
        orderOem.setPreferentialPrice(vo.getPreferentialPrice());

        if(StringUtils.isNotEmpty(vo.getPartnerCode())){
            orderOem.setPartnerCode(vo.getPartnerCode());
        }else{
            orderOem.setPartnerCode(vo.getPartnerFinancial());
        }

        //
        //0 未提交 1 已提交 2已取消
        orderOem.setCheckStatus(Constant.PMS_ORDER_OEM_CHECK_STATUS_UNSUBMIT);
        orderOem.setType(partnerInfoRespVO.getType());

        String[] customPackCodeArray = vo.getCustomPackCodes().split(",");

        CustomPackDetailsReqVO customPackDetailsReqVO = new CustomPackDetailsReqVO();
        customPackDetailsReqVO.setCustomPackCodes(customPackCodeArray);
        if(customPackCodeArray!=null&&customPackCodeArray.length>0){
            List<CustomPackDetailsRespVO> customPackDetailsRespVO = orderOemManageCustomerServiceImpl.queryCustomPackDetails(customPackDetailsReqVO);
            //将装包数据明细存储为JSON字符串
            String customPackDetails = JSONObject.toJSONString(customPackDetailsRespVO);
            orderOem.setCustomPackDetails(customPackDetails);
        }


        orderOem.setCreateBy(loginInfo.getUserCode());

        boolean isSuccess = orderOemServiceImpl.save(orderOem);
        if (!isSuccess) {
            logger.info("保存批售单主单失败，事务回滚！");
            throw new RuntimeException("保存批售单主单失败，事务回滚！");
        }

        OrderVehicleSubmitReqVO orderVehicleSubmitReqVO = new OrderVehicleSubmitReqVO();
        List<String> orderIds = new ArrayList<>();
        orderIds.add(psCode);
        orderVehicleSubmitReqVO.setOrderIds(orderIds);
        orderVehicleSubmitReqVO.setUserCode(vo.getUserCode());
        orderVehicleSubmitReqVO.setDiscountProportion(orderOem.getDiscountProportion());
        orderVehicleSubmitReqVO.setSpecialDiscountProportion(orderOem.getSpecialDiscountProportion());

        orderVehicleSubmitReqVO.setDetailId(vo.getDetailId());
        orderVehicleSubmitReqVO.setPartnerCode(vo.getPartnerCode());
        orderVehicleSubmitReqVO.setPartnerFinance(vo.getPartnerFinancial());
        orderVehicleSubmitReqVO.setVipId(vo.getVipId());
        orderVehicleSubmitReqVO.setBusinessType(vo.getBusinessType());
        orderVehicleSubmitReqVO.setSubmitType(vo.getSubmitType());
        orderVehicleSubmitReqVO.setType(vo.getType());
        submitOrderVehicleByVip(orderVehicleSubmitReqVO);

    }

    /**
     * 订单管理主数据查询
     *
     * @param vo        查询条件
     * @param pageIndex 当前页
     * @param pageSize  每页显示数据行数
     * @return
     */
    @Override
    @Transactional
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderForPage(OrderVehicleManagerDetailsReqVO vo, int pageIndex, int pageSize) {
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = orderVehicleServiceImpl.queryOrderForPage(vo, pageIndex, pageSize);

        return pageInfo;
    }

    /**
     * 订单管理明细查询
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public OrderVehicleDetailsRespVO queryOrderVehicleDetails(OrderVehicleDetailsReqVO vo) {
        OrderVehicleDetailsRespVO details = orderVehicleServiceImpl.queryOrderVehicleDetails(vo);
        return details;
    }

    /**
     * 订单取消
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean cancelOrderVehicle(OrderCancelReqVO vo) {
        List<OrderVehicle> orderVehicles = new ArrayList<>();
        if (vo == null || vo.getOrderCarIds() == null) {
            logger.info("vo对象或vo.getOrderCarIds对象为空，更新失败！");
            throw new RuntimeException("vo对象或vo.getOrderCarIds对象为空，更新失败！");
        }
        for (String orderCarId : vo.getOrderCarIds()) {

//            OrderVehicle orderVehicle = new OrderVehicle();
//            orderVehicle.setOrderCarId(orderCarId);
//            orderVehicle.setCheckStatus();
            QueryWrapper qw = new QueryWrapper();
            qw.eq("ORDER_CAR_ID", orderCarId);
            qw.eq("CHECK_STATUS", Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_WAIT_AUDIT);
            OrderCancelReason tmp = orderCancelReasonServiceImpl.getOne(qw);
            if (tmp != null) {
                logger.info("该订单已提交了取消申请，请勿重复提交！");
                throw new RuntimeException("该订单已提交了取消申请，请勿重复提交！");
            }


            OrderCancelReason orderCancelReason = new OrderCancelReason();
            String cancelId = codeCreateServiceImpl.createCode("OCL", CodeCreateServiceImpl.DATE_FORMAT_TWO, 10);
            orderCancelReason.setCancelId(cancelId);
            orderCancelReason.setOrderCarId(orderCarId);
            orderCancelReason.setCreateBy(vo.getUserCode());
            orderCancelReason.setInfo(vo.getInfo());
            orderCancelReason.setCheckStatus(Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_WAIT_AUDIT);
            boolean orderCancelReasonSuccess = orderCancelReasonServiceImpl.save(orderCancelReason);

            if (!orderCancelReasonSuccess) {
                logger.error("取消订单,更新订单表失败，事务回滚！");
                throw new RuntimeException("取消订单，更新订单表失败，事务回滚！");
            }
            //
            //保存附件信息
            for (int i = 0; vo.getUrl() != null && i < vo.getUrl().size(); i++) {
                AttachReqVO attachReqVO = new AttachReqVO();
                attachReqVO.setBusId("pms_order_cancel_reason");
                attachReqVO.setBusSubId(cancelId);
                attachReqVO.setFileName("附件");
                attachReqVO.setPicPath(vo.getUrl().get(i));
                boolean attachSuccess = stosAttachDubboService.save(attachReqVO);

                if (!attachSuccess) {
                    logger.error("取消订单，保存附件失败，事务回滚！");
                    throw new RuntimeException("取消订单，保存附件失败，事务回滚！");
                }
            }
        }
        return true;
    }

    /**
     * 订单修改申请
     * 0 未提交
     * 1 待审核
     * 2 审核通过
     * 3 驳回
     * 4 未配车
     * 5 已配车
     * 6 待扣款
     * 7 扣款驳回
     * 8 待发运
     * 9 在途
     * 10 渠道签收
     * 11 车辆实销
     * 12 销售退车
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean updateOrderVehicl(OrderVehiclReqVO vo) {
        // 查询订单状态 CHECK_STATUS 在途车辆不允许修改订单信息

        OrderVehicle tmp = orderVehicleServiceImpl.getById(vo.getOrderCarId());

        if (tmp == null) {
            return false;
        }

        //
        //需完善，读取offline表中的car_status 状态并校验状态是否可修改
        QueryWrapper qwOffline = new QueryWrapper();
        qwOffline.eq("ZORD_NO",tmp.getZordNo());
        qwOffline.in("CAR_STATE","12FYZT","13QDSC","14QDRK","15LSCK","16LSTH","17THRK","18THCK");
        VehicleOffline vehicleOffline = vehicleOfflineServiceImpl.getOne(qwOffline);

        if(vehicleOffline != null){
            logger.info("在途、渠道商入库、销售退车车辆不允许修改订单信息！");
            throw new RuntimeException("在途、渠道商入库、销售退车车辆不允许修改订单信息！");
        }
        if (Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_RECEIVE == tmp.getCheckStatus()
                || Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_PUT_IN_STORAGE == tmp.getCheckStatus()
                || Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_RETURN_CAR == tmp.getCheckStatus()) {
            logger.info("在途、渠道商入库、销售退车车辆不允许修改订单信息！");
            throw new RuntimeException("在途、渠道商入库、销售退车车辆不允许修改订单信息！");
        }

        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_CAR_ID", vo.getOrderCarId());
        qw.eq("CHECK_STATUS",Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_WAIT_AUDIT);
        OrderModifyApply tmpOrderModifyApply = orderModifyApplyServiceImpl.getOne(qw);
        if (tmpOrderModifyApply != null) {
            logger.info("当前订单修改已提交申请，请等待审核！");
            throw new RuntimeException("当前订单修改已提交申请，请等待审核！");
        }

        OrderModifyApply orderModifyApply = new OrderModifyApply();
        String orderEditId = codeCreateServiceImpl.createCode("OED", CodeCreateServiceImpl.DATE_FORMAT_TWO, 10);
        orderModifyApply.setOrderEditId(orderEditId);
        BeanUtils.copyProperties(vo, orderModifyApply);
        orderModifyApply.setCreateBy(vo.getUserCode());
        orderModifyApply.setIsPickUp(vo.getIsPickup());
        orderModifyApply.setCheckStatus(Constant.PMS_ORDER_CANCEL_REASON_CHECK_STATUS_WAIT_AUDIT);
        orderModifyApplyServiceImpl.save(orderModifyApply);
        return true;
    }

    /**
     * 主机厂订单审批申请主数据查询
     *
     * @param vo        查询条件
     * @param pageIndex 当前页
     * @param pageSize  每页显示数据行数
     * @return
     */
    @Override
    @Transactional
    public PageInfo<OrderApproveRespVO> queryOrderApproveInfoForPage(OrderApproveReqVO vo, int pageIndex, int pageSize) {
        PageInfo<OrderApproveRespVO> pageInfo = orderApproveCustomerServiceImpl.queryOrderApproveInfoForPage(vo, pageIndex, pageSize);
        return pageInfo;
    }

    /**
     * 主机厂取消订单审核主数据查询
     *
     * @param vo        查询条件
     * @param pageIndex 当前页
     * @param pageSize  每页显示数据行数
     * @return
     */
    @Override
    @Transactional
    public PageInfo<OrderApproveCancelRespVO> queryCancelOrderApproveForPage(OrderApproveCancelReqVO vo, int pageIndex, int pageSize) {
        PageInfo<OrderApproveCancelRespVO> pageInfo = orderApproveCustomerServiceImpl.queryCancelOrderApproveForPage(vo, pageIndex, pageSize);
        return pageInfo;
    }

    /**
     * 渠道商查询订单修改审核的数据
     * @param vo
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    public PageInfo<OrderModifyApplyRespVO> queryOrderModifyApplyForPage(OrderModifyApplyReqVO vo, int pageIndex, int pageSize){
        PageInfo<OrderModifyApplyRespVO> pageInfo = orderModifyApplyServiceImpl.queryOrderModifyApplyForPage(vo,pageIndex,pageSize);
        return pageInfo;
    }

    /**
     * 主机厂订单管理订单查询
     *
     * @param vo        查询条件
     * @param pageIndex 当前页
     * @param pageSize  每页显示数据行数
     * @return
     */
    @Override
    @Transactional
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveForPage(OrderVehicleManagerDetailsReqVO vo, int pageIndex, int pageSize) {
        PageInfo<OrderVehicleManagerDetailsRespVO> pageInfo = orderVehicleServiceImpl.queryOrderApproveForPage(vo, pageIndex, pageSize);
        return pageInfo;
    }

    /**
     * 订单导出
     *
     * @param vo 查询条件
     * @return ApiResult
     */
    @Override
    public ApiResult orderExport(OrderVehicleManagerDetailsReqVO vo) {
        return  orderVehicleServiceImpl.orderExport(vo);
    }

    /**
     * 调用SAP获取渠道商资金
     *
     * @return
     */
    private PartnerAmountRespVO callSapInvokAmount(String partnerCode) {
        PartnerFundVO partnerFundVO = new PartnerFundVO();
        partnerFundVO.setKunnr(partnerCode);
        try {
            ApiResult sapResult = sapDubboServiceImpl.findPartnerFundBySap(partnerFundVO);
            if (200 != sapResult.getCode()) {
                logger.error("【主机厂订单审核通过业务】SAP接口调用，渠道商资金账户获取失败，事务回滚!");
                throw new RuntimeException(sapResult.getCode()+sapResult.getMsg());
            }
            JSONArray json = JSONArray.parseArray((String) sapResult.getData());
            PartnerAmountRespVO partnerAmountRespVO = JSON.parseObject(json.getString(0), PartnerAmountRespVO.class);
            return partnerAmountRespVO;
        } catch (Exception e) {
            logger.error("【主机厂订单审核通过业务】SAP接口调用，渠道商资金账户获取失败，事务回滚!", e);
            throw new RuntimeException("【异常】【主机厂订单审核通过业务】SAP接口调用，渠道商资金账户获取失败，事务回滚!");
        }
    }

    /**
     * 主机厂订单审核通过或驳回状态修改
     *
     * @param vo 请求数据
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public boolean setOrderCheckStatus(OrderPassReqVO vo) {

        if (vo == null || vo.getOrderCarIds() == null) {
            logger.info("vo对象或vo.getOrderCarIds对象为空，更新失败！");
            throw new RuntimeException("vo对象或vo.getOrderCarIds对象为空，更新失败！");
        }

        if (vo.getCheckStatus() == Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_MATCH_CAR) {
            //
            //表示审核通过
            for (String orderCarId : vo.getOrderCarIds()) {

                //
                //获取渠道商信息
                QueryWrapper getPartnerQW = new QueryWrapper();
                getPartnerQW.eq("ORDER_CAR_ID", orderCarId);
                OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(getPartnerQW);

                if (orderVehicle == null) {
                    logger.info("渠道商账户信息为空，请核实！");
                    throw new RuntimeException("渠道商账户信息为空，请核实！");
                }

                String partnerCode = orderVehicle.getPartnerCode();
                //Guan 如果是大客戶厂端创建的订货单则 渠道商需要更换为大客户的渠道商信息
                if(StringUtils.isNotEmpty(orderVehicle.getVipId())){
                    //查询当前orderVehicle 是否为 厂端创建大客户订单 顺带返回渠道code
                    StoVehicleExpVO expVO = stoVehicleExpService.getByOrderCarId(orderVehicle.getOrderCarId());
                    //如果为厂端的大客户订单则使用大客户所属渠道商涉及的账户
                    if(expVO!=null){
                        if(expVO.getSubmitType()==1){
                            partnerCode = expVO.getVipNo();
                        }
                    }else{
                        logger.info("订货单未关联到大客户信息，请核实！");
                        throw new RuntimeException("订货单未关联到大客户信息，请核实！");
                    }
                }

                //
                //SAP获取当前可用资金
                PartnerAmountRespVO partnerAmountRespVO = callSapInvokAmount(partnerCode);

                QueryWrapper getAmountFreezeByCondition = new QueryWrapper();
                getAmountFreezeByCondition.eq("PARTNER_CODE", partnerCode);
                getAmountFreezeByCondition.eq("CATALOG_CODE", orderVehicle.getCatalogCode());
                AmountFreeze amountFreeze = amountFreezeServiceImpl.getOne(getAmountFreezeByCondition);

                //
                //获取渠道商账户资金
                PartnerAccountInfoReqVO partnerAccountInfoReqVO = new PartnerAccountInfoReqVO();
                partnerAccountInfoReqVO.setAccountTypeCode(Constant.ACCOUNT_TYPE_CODE_CASH);
                partnerAccountInfoReqVO.setPartnerCode(partnerCode);
                PartnerAccountInfoRespVO partnerAccountInfoRespVO = partnerAccountInfoServiceImpl.queryPartnerAccountInfo(partnerAccountInfoReqVO);

                if (partnerAccountInfoRespVO == null) {
                    logger.info("渠道商账户信息为空，请核实！");
                    throw new RuntimeException("渠道商账户信息为空，请核实！");
                }
                if (amountFreeze == null) {
                    amountFreeze = new AmountFreeze();
                    amountFreeze.setFreezeAmount(new BigDecimal(0));

                   logger.info("渠道商单车需冻结主数据信息为空，单车需冻结资金使用默认值0！");
//                    throw new RuntimeException("渠道商单车需冻结主数据信息为空，请核实！");
                }
                //
                //当前可用金额
                BigDecimal cashbal = new BigDecimal(Strings.isNotEmpty(partnerAmountRespVO.getCashbal()) ? partnerAmountRespVO.getCashbal() : "0");
                //
                //需冻结金额
                BigDecimal needFreezeAmount = amountFreeze.getFreezeAmount();

                //
                //当前可用金额 >= 经销商已冻结金额 + 单车需冻结金额

                //
                //已冻结金额
                BigDecimal frozenAmount = partnerAccountInfoRespVO.getFrozenAmount() == null ? new BigDecimal(0) : partnerAccountInfoRespVO.getFrozenAmount();
                if (cashbal.compareTo(needFreezeAmount.add(frozenAmount)) < 0) {
                    logger.info("渠道商当前可用金额小于已冻结金额，请核实！");
                    throw new RuntimeException("渠道商当前可用金额小于已冻结金额，请核实！");
                }

                //ƒ
                //更新渠道商资金账户
                PartnerAccount partnerAccount = new PartnerAccount();
                partnerAccount.setFrozenAmount(needFreezeAmount.add(frozenAmount));
                partnerAccount.setAccountBalance(new BigDecimal(partnerAmountRespVO.getCashbal()));
                partnerAccount.setAccountAmount(new BigDecimal(partnerAmountRespVO.getCashtotal()));

                QueryWrapper partnerAccountQW = new QueryWrapper();
                partnerAccountQW.eq("PARTNER_CODE", partnerCode);
                partnerAccountQW.eq("ACCOUNT_TYPE_CODE", Constant.ACCOUNT_TYPE_CODE_CASH);

                partnerAccountInfoServiceImpl.update(partnerAccount, partnerAccountQW);

                OrderVehicle orderVehicleStatus = new OrderVehicle();
                orderVehicleStatus.setUpdateBy(vo.getUserCode());
                orderVehicleStatus.setOrderCarId(orderCarId);
                orderVehicleStatus.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_MATCH_CAR);
                orderVehicleStatus.setCheckDate(new Date());
                boolean updateSuccess = orderVehicleServiceImpl.updateById(orderVehicleStatus);

                if (!updateSuccess) {
                    logger.info("主机厂订单审核通过'状态'修改失败,事务回滚！");
                    throw new RuntimeException("主机厂订单审核通过'状态'修改失败,事务回滚！");
                }
                //修改返利信息
                updateSuccess = updateOrderRebatbyOrderCarId(vo,orderCarId);
                if (!updateSuccess) {
                    logger.info("返利信息修改失败,事务回滚！");
                    throw new RuntimeException("返利信息修改失败,事务回滚！");
                }

                QueryWrapper qwPartnerAccount = new QueryWrapper();
                qwPartnerAccount.eq("PARTNER_CODE",partnerCode);
                qwPartnerAccount.eq("ACCOUNT_TYPE_CODE",DMSEnumsEntity.PaywayType.CASH.getKey());
                PartnerAccount tmp = partnerAccountInfoServiceImpl.getOne(qwPartnerAccount);
                //
                //记录渠道商资金冻结流水
                PartnerAmountFreezeFlow flow = new PartnerAmountFreezeFlow();
                flow.setPartnerCode(partnerCode); //渠道商编码
                flow.setCreateBy(vo.getUserCode());
                flow.setOrderCarId(orderCarId); // 订货单号
                flow.setAccountCode(tmp.getAccountCode());  //渠道商账户
                flow.setFreezeAmount(needFreezeAmount);  //最后需冻结的资金
                flow.setFreezeStatus(DMSEnumsEntity.YesNo.YES.getStatus());    //表示冻结
                flow.setVin(orderVehicle.getVin()); //VIN码
                partnerAmountFreezeFlowServiceImpl.save(flow);
            }
        } else if (vo.getCheckStatus() == Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_REJECT) {
            //
            //表示驳回,驳回订单需要填写驳回原因
            for (String orderCarId : vo.getOrderCarIds()) {
                OrderVehicle orderVehicle = new OrderVehicle();
                orderVehicle.setUpdateBy(vo.getUserCode());
                orderVehicle.setOrderCarId(orderCarId);
                orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_REJECT);
                orderVehicle.setRejectInfo(vo.getRejectInfo());
                orderVehicle.setUpdateBy(vo.getUserCode());
                orderVehicle.setCheckDate(new Date());

                boolean updateSuccess = orderVehicleServiceImpl.updateById(orderVehicle);

//              OrderVehicleReject reject = new OrderVehicleReject();
//              reject.setRejectInfo(vo.getRejectInfo());
//              reject.setOrderCarId(orderCarId);
//              reject.setCreateBy(vo.getUserCode());
//
//              boolean saveSuccess = orderVehicleRejectServiceImpl.save(reject);

                if (!(updateSuccess)) {
                    logger.info("主机厂订单审核驳回失败,事务回滚！");
                    throw new RuntimeException("主机厂订单审核驳回失败,事务回滚！");
                }
            }
        }
        return true;
    }

    /**
     * 主机厂订单管理订单设置优先级
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean setOrderLevel(OrderSetLevelReqVO vo) {
        if (vo == null || vo.getOrderCarIds() == null) {
            logger.info("vo对象或vo.getOrderCarIds对象为空，更新失败！");
            throw new RuntimeException("vo对象或vo.getOrderCarIds对象为空，更新失败！");
        }

        List<OrderVehicle> pmsOrderVehicles = new ArrayList<>();
        for (String orderCarId : vo.getOrderCarIds()) {
            OrderVehicle orderVehicle = new OrderVehicle();
            orderVehicle.setOrderCarId(orderCarId);
            orderVehicle.setUpdateBy(vo.getUserCode());
            orderVehicle.setPriorityLevel(vo.getPriorityLevel());
            pmsOrderVehicles.add(orderVehicle);
        }

        return orderVehicleServiceImpl.updateBatchById(pmsOrderVehicles);
    }

    @Override
    @Transactional
    public OrderApproveDetailsRespVO queryOrderApproveDetails(OrderApproveDetailsReqVO vo) {
        OrderApproveCarDetailsRespVO carDetailsRespVO = orderApproveCustomerServiceImpl.queryCarDetails(vo);
        OrderApproveVehicleDetailsRespVO vehicleDetailsRespVO = orderApproveCustomerServiceImpl.queryOrderDetails(vo);
        OrderApprovePartnerDetailsRespVO partnerDetailsRespVO = orderApproveCustomerServiceImpl.queryPartnerDetails(vo);
        //List<OrderApproveCustomPackDetailsRespVO> customPackDetailsRespVOList = orderApproveCustomerServiceImpl.queryCustomPackDetails(vo);

        BigDecimal rebateAccount = vehicleDetailsRespVO.getRebateAccount();
        BigDecimal rebateProportion = vehicleDetailsRespVO.getRebateProportion();
        BigDecimal settlementPrice =vehicleDetailsRespVO.getSettlementPrice();
        //计算真实结算价格
        if(rebateAccount==null && rebateProportion==null ){
            vehicleDetailsRespVO.setRealSettlementPrice(settlementPrice);
        }else{

            // 返利金额不为空  实际结算金额 = 结算价-返利使用金额
            if(rebateAccount!=null){
                vehicleDetailsRespVO.setRealSettlementPrice(settlementPrice.subtract(rebateAccount));
            }
            //返利比例不为空  实际结算金额 = 结算价-返利使用比例*结算价
            if (rebateProportion != null) {
                BigDecimal tempPirce = rebateProportion.multiply(settlementPrice).divide(new BigDecimal(100),2);
                vehicleDetailsRespVO.setRealSettlementPrice(settlementPrice.subtract(tempPirce));
            }
        }



        OrderApproveDetailsRespVO respVO = new OrderApproveDetailsRespVO();
        respVO.setOrderVehicle(vehicleDetailsRespVO);
        respVO.setPartner(partnerDetailsRespVO);
        //respVO.setCustomPacks(customPackDetailsRespVOList);
        respVO.setCarInfo(carDetailsRespVO);

        return respVO;
    }

    /**
     * 库存资源查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    public PageInfo<StockResourceRespVO> queryStockResource(StockOrProductionLineResourceReqVO vo, int pageNum, int pageSize) {

        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_CAR_ID", vo.getOrderCarId());

        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qw);
        if (orderVehicle == null) {
            return null;
        }

        vo.setCustomPackCode(orderVehicle.getCustomPackCodes());
        vo.setProductCode(orderVehicle.getProductCode());

        PageInfo<StockResourceRespVO> pageInfo = orderVehicleServiceImpl.queryStockResource(vo, pageNum, pageSize);
        return pageInfo;
    }

    /**
     * 产线资源查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    public PageInfo<ProductionLineResourceRespVO> queryProductionLineResource(StockOrProductionLineResourceReqVO vo, int pageNum, int pageSize) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_CAR_ID", vo.getOrderCarId());

        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qw);

        if (orderVehicle == null) {
            return null;
        }
        vo.setCustomPackCode(orderVehicle.getCustomPackCodes());
        vo.setProductCode(orderVehicle.getProductCode());

        PageInfo<ProductionLineResourceRespVO> pageInfo = orderVehicleServiceImpl.queryProductionLineResource(vo, pageNum, pageSize);

        return pageInfo;
    }

    /**
     * 订单配车
     *
     * @return
     */
    @Override
    @Transactional
    public boolean updateVinOfOrderVehicle(StockOrProductionLineResourceReqVO vo) {
//        OrderVehicle orderVehicle = new OrderVehicle();
//        orderVehicle.setOrderCarId(vo.getOrderCarId());
//        orderVehicle.setVin(vo.getVin());
//        orderVehicleServiceImpl.updateById(orderVehicle);
        return true;
    }

    /**
     * 合格证管理主数据查询
     *
     * @param vo       查询条件
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional
    public PageInfo<VehicleCertRespVO> queryVehicleCert(VehicleCertReqVO vo, int pageNum, int pageSize) {
        PageInfo<VehicleCertRespVO> pageInfo = vehicleCertCustomerServiceImpl.queryVehicleCert(vo, pageNum, pageSize);

        return pageInfo;
    }

    @Override
    @Transactional
    public List<NoMatchCarOrderForDownloadRespVO> queryNoMatchCarOrderForDownload(){
        return orderVehicleServiceImpl.queryNoMatchCarOrderForDownload();
    }

    @Override
    public PageInfo<ProductionLineResourceRespVO> pageProductionLineResourceByVehicleCode(StockOrProductionLineResourceReqVO vo, int pageNum, int pageSize) {

        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_CAR_ID", vo.getOrderCarId());

        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qw);

        if (orderVehicle == null) {
            return null;
        }
        vo.setCustomPackCode(orderVehicle.getCustomPackCodes());
        //vo.setProductCode(orderVehicle.getProductCode());
        vo.setCatalogCode(orderVehicle.getCatalogCode());
        PageInfo<ProductionLineResourceRespVO> pageInfo = orderVehicleServiceImpl.pageProductionLineResourceByVehicleCode(vo, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    public PageInfo<StockResourceRespVO> queryStockResourceByVehicleCode(StockOrProductionLineResourceReqVO vo, int pageNum, int pageSize) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_CAR_ID", vo.getOrderCarId());

        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qw);
        if (orderVehicle == null) {
            return null;
        }

        vo.setCustomPackCode(orderVehicle.getCustomPackCodes());
        vo.setProductCode(orderVehicle.getProductCode());
        vo.setCatalogCode(orderVehicle.getCatalogCode());
        vo.setColorCodeIn(vo.getColorCodeIn());
        vo.setColorCodeOut(vo.getColorCodeOut());
        PageInfo<StockResourceRespVO> pageInfo = orderVehicleServiceImpl.queryStockResourceByVehicleCode(vo, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean handMatchCarVip(OrderApproveHandMatchCarReqVO vo) {
        QueryWrapper qwOrderVehicle = new QueryWrapper();
        qwOrderVehicle.eq("ORDER_CAR_ID", vo.getOrderCarId());
        qwOrderVehicle.in("CHECK_STATUS",
                Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_MATCH_CAR,
                Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_DEDUCT_REJECT);

        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);

        if (orderVehicle == null) {
            logger.error("获取单据信息为空，手动配车失败！");
            throw new RuntimeException("获取单据信息为空，手动配车失败！");
        }

        VehicleOffline offline = new VehicleOffline();
        offline.setVehicleIsFrozen(Constant.PMS_VEHICLE_IS_FROZEN);
        //表示销售配车,填写原因
        offline.setFrozenReasonKey(1);
        offline.setIsLock(Constant.PMS_VEHICLE_IS_LOCK_LOCK);
        QueryWrapper qw = new QueryWrapper();
        qw.eq("ZORD_NO", vo.getZordNo());
        boolean offlineUpdate = vehicleOfflineServiceImpl.update(offline, qw);

        VehicleOffline queryTmp = vehicleOfflineServiceImpl.getOne(qw);

        QueryWrapper orderVehicleQW = new QueryWrapper();
        orderVehicleQW.eq("ORDER_CAR_ID", vo.getOrderCarId());
        orderVehicle.setZordNo(vo.getZordNo());
        orderVehicle.setVin(queryTmp.getVin());
        orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_DEDUCT);

        if(StringUtils.isNotEmpty(orderVehicle.getCustomOrderNo())){
            OrderCustomerVO ocv = orderCustomerService.getByOrderCustomerNo(orderVehicle.getCustomOrderNo());
            ocv.setVin(queryTmp.getVin());
            OrderCustomer oc = new OrderCustomer();
            BeanUtils.copyProperties(ocv,oc);
            orderCustomerService.updateById(oc);
        }

        boolean orderVehicleUpdate = orderVehicleServiceImpl.update(orderVehicle, orderVehicleQW);

        if (!(offlineUpdate && orderVehicleUpdate)) {
            logger.error("手动配车失败，事务回滚！");
            throw new RuntimeException("手动配车失败，事务回滚！");
        }

        ////// 匹配现车资源时调用SAP订单接口
        if (DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals(queryTmp.getCarState())) {
            CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO =  getCallSapInvokVehicleBatchOrderReqVO( orderVehicle);

            //
            //大客户进行渠道信息拦截
            if(StringUtils.isNotEmpty(orderVehicle.getVipId())){
                //查询当前orderVehicle 是否为 厂端创建大客户订单 顺带返回渠道code
                StoVehicleExpVO expVO = stoVehicleExpService.getByOrderCarId(orderVehicle.getOrderCarId());
                //如果为厂端的大客户订单则使用大客户所属渠道商涉及的账户
                if(expVO!=null){
                    if(expVO.getSubmitType()==1){
                        callSapInvokVehicleBatchOrderReqVO.setPartnerCode(expVO.getVipNo());
                    }
                }else{
                    logger.info("订货单未关联到大客户信息，请核实！");
                    throw new RuntimeException("订货单未关联到大客户信息，请核实！");
                }
            }

            //调用资金业务接口，获取特殊折扣
            callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);
        }
        return true;
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckForPageVip(OrderVehicleManagerDetailsReqVO vo, int pageNum, int pageSize) {
        return orderVehicleServiceImpl.queryOrderApproveCheckForPageVip(vo, pageNum, pageSize);
    }

    @Override
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckExpienceForPage(OrderVehicleManagerDetailsReqVO vo, int pageNum, int pageSize) {
        return orderVehicleServiceImpl.queryOrderApproveCheckExpienceForPage(vo, pageNum, pageSize);
    }

    @Override
    public List<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckExpienceForDownload(OrderVehicleManagerDetailsReqVO vo) {
        return orderVehicleServiceImpl.queryOrderApproveCheckExpienceForDownload(vo);
    }

    /**
     * 自动配车
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public ApiResult orderAutoMatchCar(OrderApproveAutoMatchCarReqVO vo) {

        if (vo == null || vo.getOrderCarIds() == null) {
            logger.info("VO对象为null，自动配车失败！");
            throw new RuntimeException("VO对象为null,自动配车失败！");
        }

        for (String orderCarId : vo.getOrderCarIds()) {
            //
            //1.订单根据车型、车系、配置、内外颜色查询优先匹配未配车的库存
            //2.匹配车辆下线表再库存中且未配车的车辆
            //3.如果查询的数据集合中没有相关车辆数据则去产线上找产线车辆进行匹配

            QueryWrapper qwOrderVehicle = new QueryWrapper();
            qwOrderVehicle.eq("ORDER_CAR_ID", orderCarId);
            qwOrderVehicle.in("CHECK_STATUS",
                    Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_MATCH_CAR,
                    Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_DEDUCT_REJECT);

            OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);

            if (orderVehicle == null) {
                continue;
            }
            StockOrProductionLineResourceReqVO stockOrProductionLineResourceReqVO = new StockOrProductionLineResourceReqVO();
            stockOrProductionLineResourceReqVO.setProductCode(orderVehicle.getProductCode());
            stockOrProductionLineResourceReqVO.setCustomPackCode(orderVehicle.getCustomPackCodes());
            stockOrProductionLineResourceReqVO.setOrderCarId(orderVehicle.getOrderCarId());
            PageInfo<StockResourceRespVO> stockCars = orderVehicleServiceImpl.queryStockResource(stockOrProductionLineResourceReqVO, 1, 1);
            if (stockCars != null && stockCars.getList().size() > 0) {
                autoMatchCarEx(stockCars.getList().get(0).getZordNo(), orderCarId, stockCars.getList().get(0).getVin(),orderVehicle.getVehiclePurpose());
            } else {
                //
                //匹配产线车辆
                PageInfo<ProductionLineResourceRespVO> productionLineCars = orderVehicleServiceImpl.queryProductionLineResource(stockOrProductionLineResourceReqVO, 1, 1);

                if (productionLineCars != null && productionLineCars.getList().size() > 0) {
                    autoMatchCarEx(productionLineCars.getList().get(0).getZordNo(), orderCarId, productionLineCars.getList().get(0).getVin(),orderVehicle.getVehiclePurpose());
                }else{
                    //
                    //若库存资源以及产线资源都没有相关车辆，则给用户提示
                    return ResponseUtil.fail(901,"自动配车失败，查询没有相关库存及产线资源！ ");
                }
            }
        }

        return ResponseUtil.ok();
    }

    private void autoMatchCarEx(String zordNo, String orderCarId, String vin,Integer vehiclePurpose) {
        //
        //匹配库存车辆
        QueryWrapper qw = new QueryWrapper();
        qw.eq("ZORD_NO", zordNo);

        VehicleOffline offline = new VehicleOffline();
        offline.setIsLock(Constant.PMS_VEHICLE_IS_LOCK_LOCK);
        offline.setVehicleIsFrozen(Constant.PMS_VEHICLE_IS_FROZEN);
        //表示销售配车,填写原因
        offline.setFrozenReasonKey(1);
        offline.setVehiclePurpose(vehiclePurpose);
        boolean offlineUpdate = vehicleOfflineServiceImpl.update(offline, qw);

        QueryWrapper qwOrderVehicle = new QueryWrapper();
        qwOrderVehicle.eq("ORDER_CAR_ID", orderCarId);
        OrderVehicle orderVehicle = new OrderVehicle();
        orderVehicle.setZordNo(zordNo);
        orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_DEDUCT);
        orderVehicle.setMatchStatus(Constant.PMS_ORDER_VEHICLE_MATCH_STATUS_MATCH_CAR);
        orderVehicle.setVin(vin);
        boolean orderVehhicleUpdate = orderVehicleServiceImpl.update(orderVehicle, qwOrderVehicle);

        if (!(offlineUpdate && orderVehhicleUpdate)) {
            logger.error("配车失败，事务回滚！");
            throw new RuntimeException("配车失败，事务回滚！");
        }

        VehicleOffline queryTmp = vehicleOfflineServiceImpl.getOne(qw);


        /**
         * 如果有零售单号 ，并且配车VIN不为空
         * 更新零售单上VIN信息
         * */

        QueryWrapper orderqw = new QueryWrapper();
        orderqw.eq("ORDER_CAR_ID", orderCarId);
        orderVehicle =  orderVehicleServiceImpl.getOne(orderqw);
        if(orderVehicle.getCustomOrderNo()!=null&&queryTmp.getVin()!=null){

            orderCustomerService.updateVinByOrderCutomerNo(orderVehicle.getCustomOrderNo(),queryTmp.getVin());
        }


        ////// 匹配现车资源时调用SAP订单接口
        if (DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals(queryTmp.getCarState())) {
            orderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);
            CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO = getCallSapInvokVehicleBatchOrderReqVO( orderVehicle);
            //
            //调用资金业务接口，获取特殊折扣

            //大客户订单拦截
            if(StringUtils.isNotEmpty(orderVehicle.getVipId())){
                //查询当前orderVehicle 是否为 厂端创建大客户订单 顺带返回渠道code
                StoVehicleExpVO expVO = stoVehicleExpService.getByOrderCarId(orderVehicle.getOrderCarId());
                //如果为厂端的大客户订单则使用大客户所属渠道商涉及的账户
                if(expVO!=null){
                    if(expVO.getSubmitType()==1){
                        callSapInvokVehicleBatchOrderReqVO.setPartnerCode(expVO.getVipNo());
                    }
                }else{
                    logger.info("订货单未关联到大客户信息，请核实！");
                    throw new RuntimeException("订货单未关联到大客户信息，请核实！");
                }
            }

            callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);

            // 发送待生产过点信息到APP
            if (!DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals(queryTmp.getCarState()) && !StringUtils
                .isEmpty(orderVehicle.getCustomOrderNo())) {
                try {
                    orderState2App(orderVehicle.getCustomOrderNo(), queryTmp.getVin());
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("手动配车失败，事务回滚！" + e.getMessage());
                    throw new RuntimeException("手动配车失败，事务回滚！");
                }
            }
        }
    }

    /**
     * 取消配车绑定
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean cancelMatchCar(OrderApproveAutoMatchCarReqVO vo) {

        if (vo == null || vo.getOrderCarIds() == null) {
            logger.info("VO对象为null，取消配车绑定！");
            throw new RuntimeException("VO对象为null,取消配车绑定！");
        }

        for (int i = 0; i < vo.getOrderCarIds().size(); i++) {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("ORDER_CAR_ID", vo.getOrderCarIds().get(i));
            OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qw);
            if (orderVehicle == null) {
                continue;
            }
            //
            //计划单号
            String zordNo = orderVehicle.getZordNo();

            if (zordNo == null) {
                continue;
            }
            orderVehicle.setVin("");
            orderVehicle.setZordNo("");
            orderVehicle.setMatchStatus(Constant.PMS_ORDER_VEHICLE_MATCH_STATUS_NO_MATCH_CAR);
            boolean orderVehicleSuccess = orderVehicleServiceImpl.update(orderVehicle, qw);

            QueryWrapper qwVehicleOffline = new QueryWrapper();
            qwVehicleOffline.eq("ZORD_NO", zordNo); //更新配车状态为未配车
            VehicleOffline vehicleOffline = new VehicleOffline();
            vehicleOffline.setZordNo(zordNo);
            vehicleOffline.setVehicleIsFrozen(Constant.PMS_VEHICLE_IS_NOT_FROZEN);
            //表示销售配车，释放原因
            vehicleOffline.setFrozenReasonKey(-1);
            boolean vehicleOfflineSuccess = vehicleOfflineServiceImpl.update(vehicleOffline, qwVehicleOffline);

            if (!(orderVehicleSuccess && vehicleOfflineSuccess)) {
                logger.error("取消配车绑定失败，事务回滚！");
                throw new RuntimeException("取消配车绑定失败，事务回滚！");
            }
        }
        return true;
    }

    /**
     * 手动配车
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean handMatchCar(OrderApproveHandMatchCarReqVO vo) {

        QueryWrapper qwOrderVehicle = new QueryWrapper();
        qwOrderVehicle.eq("ORDER_CAR_ID", vo.getOrderCarId());
        qwOrderVehicle.in("CHECK_STATUS",
                Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_MATCH_CAR,
                Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_DEDUCT_REJECT);

        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);

        if (orderVehicle == null) {
            logger.error("获取单据信息为空，手动配车失败！");
            throw new RuntimeException("获取单据信息为空，手动配车失败！");
        }

        VehicleOffline offline = new VehicleOffline();
        offline.setVehicleIsFrozen(Constant.PMS_VEHICLE_IS_FROZEN);
        //表示销售配车,填写原因
        offline.setFrozenReasonKey(1);
        offline.setIsLock(Constant.PMS_VEHICLE_IS_LOCK_LOCK);
        offline.setVehiclePurpose(orderVehicle.getVehiclePurpose());
        QueryWrapper qw = new QueryWrapper();
        qw.eq("ZORD_NO", vo.getZordNo());

        VehicleOffline queryTmp = vehicleOfflineServiceImpl.getOne(qw);

        qw.eq("VEHICLE_IS_FROZEN", 0);
        qw.eq("IS_LOCK", 0);
        boolean offlineUpdate = vehicleOfflineServiceImpl.update(offline, qw);
        if (!offlineUpdate) {
            logger.error("车辆冲突，手动配车失败，请刷新后再试");
            throw new RuntimeException("车辆冲突，手动配车失败，请刷新后再试");
        }


        /**
        * 如果有零售单号 ，并且配车VIN不为空
         * 更新零售单上VIN信息
         * */
        if(orderVehicle.getCustomOrderNo()!=null&&queryTmp.getVin()!=null){

            orderCustomerService.updateVinByOrderCutomerNo(orderVehicle.getCustomOrderNo(),queryTmp.getVin());
        }


        QueryWrapper orderVehicleQW = new QueryWrapper();
        orderVehicleQW.eq("ORDER_CAR_ID", vo.getOrderCarId());
        orderVehicle.setZordNo(vo.getZordNo());
        orderVehicle.setVin(queryTmp.getVin());
        orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_DEDUCT);
        boolean orderVehicleUpdate = orderVehicleServiceImpl.update(orderVehicle, orderVehicleQW);

        if (!(offlineUpdate && orderVehicleUpdate)) {
            logger.error("手动配车失败，事务回滚！");
            throw new RuntimeException("手动配车失败，事务回滚！");
        }

        // 发送待生产过点信息到APP
        if (!DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals(queryTmp.getCarState()) && !StringUtils
            .isEmpty(orderVehicle.getCustomOrderNo())) {
            try {
                orderState2App(orderVehicle.getCustomOrderNo(), queryTmp.getVin());
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("手动配车失败，事务回滚！" + e.getMessage());
                throw new RuntimeException("手动配车失败，事务回滚！");
            }
        }


        ////// 匹配现车资源时调用SAP订单接口
        if (DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals(queryTmp.getCarState())) {
            CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO = getCallSapInvokVehicleBatchOrderReqVO( orderVehicle);

            //调用资金业务接口，获取特殊折扣
            callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);
        }
        return true;
    }
    //?
    private void getDiscountByBase(OrderVehicle orderVehicle, CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO) {
        VehiclePriceReqVO vprv = new VehiclePriceReqVO();
        vprv.setProductCode(orderVehicle.getCatalogCode());
        vprv = stoSVehiclePriceDubboServiceImpl.getDiscount(vprv);
        //如果是大客户默认有折扣，则不读取
        if(orderVehicle.getDiscountProportion()!=null){
            callSapInvokVehicleBatchOrderReqVO.setDiscountProportion(orderVehicle.getDiscountProportion()+"");
            callSapInvokVehicleBatchOrderReqVO.setSpecialDiscountProportion(orderVehicle.getSpecialDiscountProportion()+"");
        }else{
            if(vprv!=null){
                if(vprv.getUnitType()==0){
                    callSapInvokVehicleBatchOrderReqVO.setSpecialDiscountProportion(vprv.getAmount()+"");
                }else{
                    callSapInvokVehicleBatchOrderReqVO.setDiscountProportion(vprv.getAmount()+"");
                }
            }
        }
    }

    /**
     * 到批售单中查找当前VIN是否存在，如果存在表示已经配过车了
     * 如果不存在直接返回
     *
     * @param vin
     */
    @Override
    public void callSapInvokVehicleBatchOrderByVin(String vin) {
        QueryWrapper qwByVin = new QueryWrapper();
        qwByVin.eq("VIN", vin);
        qwByVin.eq("CHECK_STATUS", Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_DEDUCT);
        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qwByVin);
        if (orderVehicle == null) {
            return;
        }

        CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO = getCallSapInvokVehicleBatchOrderReqVO(orderVehicle);

        //
        //调用资金业务接口，获取特殊折扣
        callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);

    }

    /**
     * 配车成功后，调用整车批售订单接口
     */
    private void callSapInvokVehicleBatchOrder(CallSapInvokVehicleBatchOrderReqVO vo) {
        VehicleBatchOrderVO vehicleBatchOrderVO = dozerMapper.map(vo, VehicleBatchOrderVO.class);
        ApiResult sapResult = null;
        try {
             sapResult = sapDubboServiceImpl.sendVehicleBatchOrderToSap(vehicleBatchOrderVO);
            if (200 != sapResult.getCode()) {
                logger.error("SAP接口调用，整车批售订单接口，事务回滚!");

//                JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(sapResult.getData()));
//                String response = (String)json.get("response");
//                JSONObject responseJson = JSONObject.parseObject(response);

                throw new RuntimeException("【PMS-SAP】同步SAP失败,错误代码["+sapResult.getCode()+"]SAP返回结果:"+sapResult.getMsg());
            }

            JSONObject json = JSONObject.parseObject((String) sapResult.getData());

            OrderVehicle orderVehicle = new OrderVehicle();
            orderVehicle.setOrderCarId((String) json.get("bstkd"));
            orderVehicle.setSapOrderNo((String) json.get("vbeln"));
            orderVehicle.setSapHandleDate((String) json.get("zdate"));
            orderVehicle.setSapHandleTime((String) json.get("ztime"));
            orderVehicle.setSapHandleStatus((String) json.get("zstat"));
            orderVehicle.setSapHandleMessage((String) json.get("zmess"));
            boolean isSuccess = orderVehicleServiceImpl.updateById(orderVehicle);

            if (!isSuccess) {
                throw new RuntimeException("【PMS】SAP接口调用，整车批售订单接口，事务回滚!");
            }

        } catch (Exception ex) {
            logger.error("【PMS-SAP】同步SAP失败,错误代码["+sapResult.getCode()+"]SAP返回结果:"+sapResult.getMsg(),ex);
            throw new RuntimeException("【PMS-SAP】同步SAP失败,错误代码["+sapResult.getCode()+"]SAP返回结果:"+sapResult.getMsg(),ex);
        }
    }

    /**
     * 配车更换
     * <p>
     * 1,校验状态,在发运计划尚未发送至tms前,可以执行配车调整
     * 2,订单中取消原有绑定车辆,释放pms_vehicle_offline锁定状态,冻结状态
     * 3,订单中绑定新的车辆信息,锁定车辆下线表pms_vehicle_offline车辆锁定状态,冻结状态
     * 4,发送新的车辆绑定信息给SAP
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public synchronized boolean chooseMatchCar(OrderApproveHandMatchCarReqVO vo) {
        QueryWrapper qwOrderVehicle = new QueryWrapper();
        qwOrderVehicle.eq("ORDER_CAR_ID", vo.getOrderCarId());
        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(qwOrderVehicle);
        StringBuffer messge = new StringBuffer();
        String oldVin  = orderVehicle.getVin();  //原始VIN
        String zordNo = orderVehicle.getZordNo();//已配车订单中的计划单号
        if (StringUtils.isEmpty(zordNo)) {//如果么有计划单号,则说明还没有还没有配车
            logger.error("计划单号为空,尚未配车! 计划单号=====" + zordNo);
            throw new RuntimeException("计划单号为空,尚未配车!");
        }
        VehicleOffline vehicleOffline =null;
        //校验状态,在发运计划尚未发送至tms前,可以执行配车调整
        try {
            //
            //1.如果该车是产线资源，则不验证TMS是否发运
            //2.如果是库存资源，则验证TMS是否发运

            QueryWrapper checkQW = new QueryWrapper();
            checkQW.eq("CAR_STATE","10VDCRK");  //VDC入库
            checkQW.eq("ZORD_NO",zordNo);
            vehicleOffline = vehicleOfflineServiceImpl.getOne(checkQW);

            if(vehicleOffline != null) {
                boolean isSendSuccess = stoTransportPlanDubboServiceReference.checkTransportPlanIsSend(orderVehicle.getVin());

                if (!isSendSuccess) {
                    messge.append("运输计划已下发到TMS，不允许更换配车!\n");
                    logger.debug(messge.toString());
                    throw new Exception(messge.toString());

                }
            }
        } catch (Exception e) {
            messge.append("检查车辆发货状态失败\n");
            logger.debug(messge.toString(), e);
            throw new RuntimeException(messge.toString());
        }


        QueryWrapper qw = new QueryWrapper();
        qw.eq("ZORD_NO", vo.getZordNo());//新配车辆计划单号
        VehicleOffline tmp = vehicleOfflineServiceImpl.getOne(qw);//根据新计划单号获取车辆下线表车辆状态主数据

        //更新车辆订单中绑定的车辆数据 绑定新选择的车辆信息
        orderVehicle.setZordNo(vo.getZordNo());
//        orderVehicle.setMatchStatus(Constant.PMS_ORDER_VEHICLE_MATCH_STATUS_MATCH_CAR);//不使用此数据

        String tempVin = tmp.getVin();
        if (tempVin == null){
            tempVin="";
        }
        orderVehicle.setVin(tempVin);
        boolean orderVehicleUpdate = orderVehicleServiceImpl.update(orderVehicle, qwOrderVehicle);


        //在车辆下线表中,将原来绑定的车辆信息解锁  解锁和冻结置为0
        if (StringUtils.isNotEmpty(zordNo)) {
            //
            //解绑
            //将更换配车之前的车辆解绑
            QueryWrapper jieBangQW = new QueryWrapper();
            jieBangQW.eq("ZORD_NO", zordNo);
            VehicleOffline jieBang = new VehicleOffline();
            jieBang.setVehicleIsFrozen(Constant.PMS_VEHICLE_IS_NOT_FROZEN);//解除冻结
            jieBang.setIsLock(Constant.PMS_VEHICLE_IS_NOT_LOCK);//解除锁定
            //表示销售配车，释放原因
            jieBang.setFrozenReasonKey(-1);
            jieBang.setVehiclePurpose(0);
            boolean jieBangUpdate = vehicleOfflineServiceImpl.update(jieBang, jieBangQW);

            if (!jieBangUpdate) {
                logger.error("配车更换失败，事务回滚！");
                throw new RuntimeException("配车更换失败，事务回滚！");
            }
        }
        //
        //更换配车

        VehicleOffline offline = new VehicleOffline();
        offline.setVehicleIsFrozen(Constant.PMS_VEHICLE_IS_FROZEN);
        //表示销售配车,填写原因
        offline.setFrozenReasonKey(1);
        offline.setIsLock(Constant.PMS_VEHICLE_IS_LOCK_LOCK);
        offline.setVehiclePurpose(orderVehicle.getVehiclePurpose());
        qw.eq("VEHICLE_IS_FROZEN", 0);
        qw.eq("IS_LOCK", 0);
        boolean offlineUpdate = vehicleOfflineServiceImpl.update(offline, qw);

        if (!(offlineUpdate && orderVehicleUpdate)) {
            logger.error("配车更换失败，事务回滚！");
            throw new RuntimeException("配车更换失败，事务回滚！");
        }


        /**
         * 如果有零售单号 ，并且配车VIN不为空
         * 更新零售单上VIN信息
         * */
        if(orderVehicle.getCustomOrderNo()!=null&&tmp.getVin()!=null){

            orderCustomerService.updateVinByOrderCutomerNo(orderVehicle.getCustomOrderNo(),tmp.getVin());
        }


        /**
         * 发送批售单信息给SAP
         * 换车4种情况
         * 1.现车 --> 现车 : 通过（S0030035A） 订单修改接口传递
         * 2.现车 --> 厂线 : 抛异常 不支持
         * 3.厂线 --> 现车 ：通过 (S0030028A)  订单新建接口传递
         * 4.厂线 --> 厂线 ：更换时不做操作， 入库时触发订单新建接口传递
         *
         *
         */

        //查询新车数据
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ORDER_CAR_ID", vo.getOrderCarId());
        OrderVehicle newOrderVehicle = orderVehicleServiceImpl.getOne(queryWrapper);
        if ( vehicleOffline !=null && DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals( tmp.getCarState())) {
            // 1.现车 --> 现车  通过（S0030035A） 订单修改接口传递
            callSapInvokByModifyPms2Sap(newOrderVehicle);
        } else if (vehicleOffline!=null &&  !DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals(tmp.getCarState())) {
            // 2.现车 --> 厂线    抛异常 不支持
            String meaasge = "不支持将库存资源更换为产线资源，配车更换失败，事务回滚！";
            logger.error(meaasge);
            throw new RuntimeException(meaasge);
        } else if (vehicleOffline==null  &&  DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals( tmp.getCarState())  ) {
            // 3.厂线 --> 现车 通过 (S0030028A)  订单新建接口传递
            CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO = getCallSapInvokVehicleBatchOrderReqVO(newOrderVehicle);

            //大客户判断
            if(StringUtils.isNotEmpty(orderVehicle.getVipId())){
                //查询当前orderVehicle 是否为 厂端创建大客户订单 顺带返回渠道code
                StoVehicleExpVO expVO = stoVehicleExpService.getByOrderCarId(orderVehicle.getOrderCarId());
                //如果为厂端的大客户订单则使用大客户所属渠道商涉及的账户
                if(expVO!=null){
                    if(expVO.getSubmitType()==1){
                        callSapInvokVehicleBatchOrderReqVO.setPartnerCode(expVO.getVipNo());
                    }
                }else{
                    logger.info("订货单未关联到大客户信息，请核实！");
                    throw new RuntimeException("订货单未关联到大客户信息，请核实！");
                }
            }

            callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);
        }


        // 发送待生产过点信息到APP
        if (!DictConstant.VEHICLE_TURN_STATE_10VDCRK.equals(tmp.getCarState()) && !StringUtils
            .isEmpty(orderVehicle.getCustomOrderNo())) {
            try {
                orderState2App(orderVehicle.getCustomOrderNo(), tmp.getVin());
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("手动配车失败，事务回滚！" + e.getMessage());
                throw new RuntimeException("手动配车失败，事务回滚！");
            }
        }



        //发送最新的批售单信息给SAP
//        CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO = new CallSapInvokVehicleBatchOrderReqVO();
//        callSapInvokVehicleBatchOrderReqVO.setOrderCarId(orderVehicle.getOrderCarId());
//        callSapInvokVehicleBatchOrderReqVO.setOrderType(orderVehicle.getType());
//        callSapInvokVehicleBatchOrderReqVO.setPartnerCode(orderVehicle.getPartnerCode());//客户编号
//        callSapInvokVehicleBatchOrderReqVO.setOrgnize(Constant.ORGNIZE);//销售组织
//        callSapInvokVehicleBatchOrderReqVO.setPayway(orderVehicle.getPayway());
//        if("Y".equals(orderVehicle.getIsPickup())){
//            //自提
//            callSapInvokVehicleBatchOrderReqVO.setPickUp("02");
//        }else if("N".equals(orderVehicle.getIsPickup())){
//            //物流
//            callSapInvokVehicleBatchOrderReqVO.setPickUp("03");
//        }
//
//        callSapInvokVehicleBatchOrderReqVO.setOrderDate(WgrDate.date2Str(orderVehicle.getCreateDate(),"yyyyMMdd"));
//        callSapInvokVehicleBatchOrderReqVO.setCatalogCode(orderVehicle.getCatalogCode());
//        callSapInvokVehicleBatchOrderReqVO.setVin(tmp.getVin());//更换的车辆VIN
//        callSapInvokVehicleBatchOrderReqVO.setNum("1");
//        callSapInvokVehicleBatchOrderReqVO.setDispatchDate(WgrDate.date2Str(orderVehicle.getDispatchDate(),"yyyyMMdd"));
//        callSapInvokVehicleBatchOrderReqVO.setAddr(orderVehicle.getAddr());
//        callSapInvokVehicleBatchOrderReqVO.setCertAddr(orderVehicle.getAddr());
//
//        String addr = orderVehicleServiceImpl.queryStockAddrByVin(tmp.getVin());//取更换的VIN,获取新车辆的仓库地址
//        callSapInvokVehicleBatchOrderReqVO.setOutAddr(addr);
//        callSapInvokVehicleBatchOrderReqVO.setRebateProportion(orderVehicle.getRebateProportion().toString());
//        callSapInvokVehicleBatchOrderReqVO.setRebateAccount(orderVehicle.getRebateAccount().toString());
//        //特殊折扣固定值 特殊折扣
//        //callSapInvokVehicleBatchOrderReqVO.setDiscountProportion();
////        callSapInvokVehicleBatchOrderReqVO.setSpecialDiscountProportion();
//        //
//        //合格证邮寄指示符
////       callSapInvokVehicleBatchOrderReqVO.setCertfflag();
//        //资金检查指示符
//        if("1".equals(orderVehicle.getType())){
//            callSapInvokVehicleBatchOrderReqVO.setCashcheck("Y");
//        }else if("2".equals(orderVehicle.getType())){
//            callSapInvokVehicleBatchOrderReqVO.setCashcheck("N");
//        }else if("3".equals(orderVehicle.getType())){
//            //
//            //表示直销
//        }
//        callSapInvokVehicleBatchOrderReqVO.setIndicator(DMSEnumsEntity.OperateType.UPDATE.getKey());
//        //调用资金业务接口，获取特殊折扣  需冠仁给出调用特殊折扣的接口
//        callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);
        //调用整车批售单修改接口 630后
        //发送SAP成功后,修改出库计划单状态
        try {
            stoTransportPlanDubboServiceReference.cancelTransportPlanByVin(oldVin);
        } catch (Exception e) {
            logger.debug("修改出库单计划状态失败 {}", e);
            throw new RuntimeException("修改出库单计划状态失败");
        }
        return true;
    }

    @Override
    @Transactional
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveMatchCarForPage(OrderVehicleManagerDetailsReqVO vo, int pageNum, int pageSize) {
        return orderVehicleServiceImpl.queryOrderApproveMatchCarForPage(vo, pageNum, pageSize);
    }

    @Override
    @Transactional
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckForPage(OrderVehicleManagerDetailsReqVO vo, int pageNum, int pageSize) {
        return orderVehicleServiceImpl.queryOrderApproveCheckForPage(vo, pageNum, pageSize);
    }

    /**
     * 订单审核查询，订单导出
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApproveCheckForDownload(OrderVehicleManagerDetailsReqVO vo){
        return orderVehicleServiceImpl.queryOrderApproveCheckForDownload(vo);
    }

    @Override
    @Transactional
    public PageInfo<OrderVehicleManagerDetailsRespVO> queryOrderApprovePrioritySettingForPage(OrderVehicleManagerDetailsReqVO vo, int pageNum, int pageSize) {
        return orderVehicleServiceImpl.queryOrderApprovePrioritySettingForPage(vo, pageNum, pageSize);
    }

    @Override
    @Transactional
    public boolean updateOrderVehicleStatusByVin(String vin, Integer status) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("VIN", vin);
        OrderVehicle orderVehicle = new OrderVehicle();
        orderVehicle.setCheckStatus(status);
        orderVehicleServiceImpl.update(orderVehicle, qw);
        return true;
    }

    /**
     * 零售转批售
     * @param vo
     * @param loginInfo
     * @return
     */
    @Override
    @Transactional
    public ApiResult saveByOrderCustomer(OrderCustomerExOrderOemSaveReqVO vo, LoginInfo loginInfo) {


        String psCode = "";
        // 1表示渠道商创建 2表示主机厂创建 3零售转分销
        vo.setOrderCreateType(3);
        vo.setVehiclePurpose(1);
        StringBuilder sortCustomPackCode = new StringBuilder();
        if (StringUtils.isNotEmpty(vo.getCustomPackCodes())) {
            // 对选装包进行分组字符串排序再组装
            String[] customPackCodes = vo.getCustomPackCodes().split(",");
            Arrays.sort(customPackCodes);
            for (String code : customPackCodes) {
                sortCustomPackCode.append(code).append(",");
            }
            sortCustomPackCode = new StringBuilder(sortCustomPackCode.substring(0, sortCustomPackCode.length() - 1));
        }else {
            sortCustomPackCode = null;
        }
        String finalCustomPackCode = sortCustomPackCode == null ? null : sortCustomPackCode.toString();
        vo.setCustomPackCodes(finalCustomPackCode);
        psCode = savePmsOrderOemEx(vo,loginInfo);

        List<String> orderIds = vo.getOrderNoList();

        if (orderIds==null || orderIds.size()<=0) {
            return ResponseUtil.fail(-1,"零售单号为空");
        }

        OrderCustomerVO orderCustomerVO = orderCustomerService.load(orderIds.get(0));
        OrderCustomerDetailVO orderCustomerDetailVO = orderCustomerVO.getOrderCustomerDetailVO();
        if (!orderCustomerDetailVO.getVehicleCode().equals(vo.getCatalogCode()) ||
            !orderCustomerDetailVO.getColorCodeIn().equals(vo.getColorCodeIn()) ||
            !orderCustomerDetailVO.getColorCodeOut().equals(vo.getColorCodeOut())
            ){
            return ResponseUtil.fail(-1,"车型内饰外饰错误");
        }
        if (StringUtils.isNotEmpty(orderCustomerDetailVO.getCustomPackCode())){
            if (!orderCustomerDetailVO.getCustomPackCode().equals(vo.getCustomPackCodes())){
                return ResponseUtil.fail(-1,"选装包错误");
            }
        }
        if(orderIds!=null){
           if(orderIds.size()!=vo.getNum()){
              return ResponseUtil.fail(-1,"零售单号数量和零售单车数量不一致");
           }
        }

        QueryWrapper qw = new QueryWrapper();
        qw.eq("ORDER_ID", psCode);
        PmsOrderOem pmsOrderOem = orderOemServiceImpl.getOne(qw);
        pmsOrderOem.setUpdateBy(loginInfo.getUserCode());

        pmsOrderOem.setCheckStatus(Constant.PMS_ORDER_OEM_CHECK_STATUS_SUBMIT);
        if (!orderOemServiceImpl.update(pmsOrderOem, qw)) {
            logger.info("提交批售或寄售单失败，事务回滚！");
            throw new RuntimeException("提交批售或寄售单失败，事务回滚！");
        }

        for (String customerOrderNo : orderIds) {
            //保存车辆订单信息
            OrderVehicle orderVehicle = new OrderVehicle();
            BeanUtils.copyProperties(vo, orderVehicle);
            BeanUtils.copyProperties(pmsOrderOem, orderVehicle);
            //
            //生成车辆订单号
            String ocCode = codeCreateServiceImpl.createCode("OC", 4);
            orderVehicle.setOrderCarId(ocCode);
            orderVehicle.setVehiclePurpose(1);
            orderVehicle.setOrderId(pmsOrderOem.getOrderId());
            orderVehicle.setPriorityLevel(Constant.PMS_ORDER_VEHICLE_LEVEL_MIDDLE);
            orderVehicle.setCheckStatus(Constant.PMS_ORDER_VEHICLE_CHECK_STATUS_WAIT_AUDIT);
            orderVehicle.setMatchStatus(Constant.PMS_ORDER_VEHICLE_MATCH_STATUS_NO_MATCH_CAR);
            orderVehicle.setProductCode(pmsOrderOem.getProductCode());
            //获取选装包中文名
            String customPackNames = vehiclePackageDubboService.strByNodeCodeIn(StringUtil.customSqlStr(pmsOrderOem.getCustomPackCodes()));
            orderVehicle.setCustomPackNames(customPackNames);
            orderVehicle.setCustomOrderNo(customerOrderNo);
            orderVehicle.setCreateBy(loginInfo.getUserCode());
            boolean isSuccessByOrderVehicle = orderVehicleServiceImpl.save(orderVehicle);

            if (!isSuccessByOrderVehicle) {
                logger.info("提交批售单，拆单失败，事务回滚！");
                throw new RuntimeException("提交批售单，拆单失败，事务回滚！");
            }
        }
        return ResponseUtil.ok();
    }


    /**
     *  根据VIN查询是否配车，如配车则发送订单到SAP
     * @param vin VIN
     */
    @Override
    public void order2SapByVin(String vin) {
        // 查询订单
        LambdaQueryWrapper<OrderVehicle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderVehicle::getVin, vin);
        OrderVehicle orderVehicle = orderVehicleServiceImpl.getOne(lambdaQueryWrapper);
        if (orderVehicle == null) {
            return;
        }

        ////// 匹配现车资源时调用SAP订单接口
        CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO =  getCallSapInvokVehicleBatchOrderReqVO( orderVehicle);

        //调用资金业务接口，获取特殊折扣
        callSapInvokVehicleBatchOrder(callSapInvokVehicleBatchOrderReqVO);
    }

    /**
     * 发送车辆状态到APP
     * @param customOrderNo 客户订单
     * @param vin VIN
     */
    @Override
    public void orderState2App(String customOrderNo, String vin) {
        LambdaQueryWrapper<OrderCustomer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderCustomer::getOrderCustomerNo, customOrderNo);
        List<OrderCustomer> orderCustomers = orderCustomerService.list(wrapper);
        if (!CollectionUtils.isEmpty(orderCustomers)) {
            OrderStatusVO statusVO = new OrderStatusVO();
            statusVO.setZzvin(vin);
            statusVO.setRpname(DictConstant.APP_RPNAME_WAIT_PRODUCE);
            statusVO.setZpassd(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            statusVO.setStCode(DictConstant.APP_CODE_11);
            statusVO.setOrderStatus(orderCustomers.get(0).getOrderStatus().toString());
            statusVO.setOrderNo(orderCustomers.get(0).getOrderCustomerNo());
            appDubboService.sendOrderStatusPMS2APP(statusVO);
        }
    }


    /**
     * 通过 orderVehicle  生成  CallSapInvokVehicleBatchOrderReqVO
     * @param orderVehicle
     * @return
     */
    private CallSapInvokVehicleBatchOrderReqVO getCallSapInvokVehicleBatchOrderReqVO(OrderVehicle orderVehicle ) {
        CallSapInvokVehicleBatchOrderReqVO callSapInvokVehicleBatchOrderReqVO = new CallSapInvokVehicleBatchOrderReqVO();
        callSapInvokVehicleBatchOrderReqVO.setOrderCarId(orderVehicle.getOrderCarId());
        callSapInvokVehicleBatchOrderReqVO.setOrderType(orderVehicle.getType());
        //客户编号
        callSapInvokVehicleBatchOrderReqVO.setPartnerCode(orderVehicle.getPartnerCode());
        //销售组织
        callSapInvokVehicleBatchOrderReqVO.setOrgnize(Constant.ORGNIZE);
        callSapInvokVehicleBatchOrderReqVO.setPayway(orderVehicle.getPayway());
        if ("Y".equals(orderVehicle.getIsPickup())) {
            //自提
            callSapInvokVehicleBatchOrderReqVO.setPickUp("02");
        } else if ("N".equals(orderVehicle.getIsPickup())) {
            //物流
            callSapInvokVehicleBatchOrderReqVO.setPickUp("03");
        }

        callSapInvokVehicleBatchOrderReqVO.setOrderDate(WgrDate.date2Str(orderVehicle.getCreateDate(), "yyyyMMdd"));
        callSapInvokVehicleBatchOrderReqVO.setCatalogCode(orderVehicle.getCatalogCode());
        callSapInvokVehicleBatchOrderReqVO.setVin(orderVehicle.getVin());
        callSapInvokVehicleBatchOrderReqVO.setNum("1");
        callSapInvokVehicleBatchOrderReqVO.setDispatchDate(WgrDate.date2Str(orderVehicle.getDispatchDate(), "yyyyMMdd"));
        callSapInvokVehicleBatchOrderReqVO.setAddr(orderVehicle.getAddr());
        callSapInvokVehicleBatchOrderReqVO.setCertAddr(orderVehicle.getAddr());

        String addr = orderVehicleServiceImpl.queryStockAddrByVin(orderVehicle.getVin());
        callSapInvokVehicleBatchOrderReqVO.setOutAddr(addr);

        //返利比例 Guan
        if (orderVehicle.getRebateProportion() != null) {
            callSapInvokVehicleBatchOrderReqVO.setRebateProportion(orderVehicle.getRebateProportion().toString());
        }
        if (orderVehicle.getRebateAccount() != null) {
            callSapInvokVehicleBatchOrderReqVO.setRebateAccount(orderVehicle.getRebateAccount().toString());
        }

        //特殊折扣固定值 特殊折扣 Guan
        //
        if(orderVehicle.getDiscountProportion() != null){
            callSapInvokVehicleBatchOrderReqVO.setDiscountProportion(orderVehicle.getDiscountProportion().toString());
        }
        if(orderVehicle.getSpecialDiscountProportion() != null){
            callSapInvokVehicleBatchOrderReqVO.setSpecialDiscountProportion(orderVehicle.getSpecialDiscountProportion().toString());
        }

        getDiscountByBase(orderVehicle, callSapInvokVehicleBatchOrderReqVO);


        //资金检查指示符
        if ("1".equals(orderVehicle.getType())) {
            callSapInvokVehicleBatchOrderReqVO.setCashcheck("Y");
        } else if ("2".equals(orderVehicle.getType())) {
            callSapInvokVehicleBatchOrderReqVO.setCashcheck("N");
        } else if ("3".equals(orderVehicle.getType())) {//表示直销 大客户业务 Guan 2020-01-011
            callSapInvokVehicleBatchOrderReqVO.setCashcheck("Y");
            callSapInvokVehicleBatchOrderReqVO.setOrderType("3");
        }

        if (orderVehicle.getVehiclePurpose() == 2 || orderVehicle.getVehiclePurpose() == 3 || orderVehicle.getVehiclePurpose() == 4) {
            callSapInvokVehicleBatchOrderReqVO.setOrderType("11");
        }

        callSapInvokVehicleBatchOrderReqVO.setIndicator(DMSEnumsEntity.OperateType.INSERT.getKey());

        return  callSapInvokVehicleBatchOrderReqVO;
    }

    /**
     * 厂端修改订单返利
     * @param vo
     * @return
     */

    public boolean updateOrderRebatbyOrderCarId(OrderPassReqVO vo ,String orderCarId ) {

        UpdateWrapper<OrderVehicle> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ORDER_CAR_ID", orderCarId);
        OrderVehicle orderVehicle = new OrderVehicle();
        //返利比例
        updateWrapper.set("REBATE_ACCOUNT",vo.getRebateAccount());
        //返利金额
        updateWrapper.set("REBATE_PROPORTION",vo.getRebateProportion());
        boolean flag = orderVehicleServiceImpl.update(orderVehicle, updateWrapper);
        String message = "修改订单返利信息失败，事务回滚";
        if (!flag) {
            logger.info(message);
            throw new RuntimeException(message);
        }
       return  true;
    }
}
